标签:一个 去重 items item 完成 循环 etc leetcode dict
1、给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
import collections def frequencySort(s): dic = dict(collections.Counter(s)) res = sorted(dic.items(),key = lambda item:item[1],reverse = True) temp = "" for i in res: temp +=i[0]*i[1] return temp s = "tree" print(frequencySort(s))
3: 三数之和。
def threeSum(nums): res = [] nums.sort() n = len(nums) #如果数组长度小于3,也就不存在三数之和,返回[] if n<3: return res #遍历数组: for i in range(n): #数组已完成排序,i 之后的元素不存在三数之和=0的情况 if nums[i]>0: return res #跳过相邻的重复元素。 if (i>0 and nums[i]==nums[i-1]): continue #初始化指针:令 i<l<r,然后进入循环。 l = i+1 r = n-1 while l<r: sum = nums[i]+nums[l]+nums[r] if sum==0: res.append([nums[i],nums[l],nums[r]]) #去重 while (l<r and nums[l]==nums[l+1]): l = l+1 while (l<r and nums[r]==nums[r-1]): r = r-1 l = l+1 r = r-1 elif sum>0: r = r-1 else: l = l+1 return res nums = [-1, 0, 1, 2, -1, -4] print(threeSum(nums))
标签:一个 去重 items item 完成 循环 etc leetcode dict
原文地址:https://www.cnblogs.com/yijierui/p/13235814.html