一、两数之和
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ #对应每个测试案例,输出两个数,小的先输出。 # ls = [] # if not isinstance(nums, list): # return ls # for i, v in enumerate(nums): # for v1 in nums[i:]: # if (v + v1) == target: # ls.append([v,v1]) # if ls: # return ls[0] # else: # return ls keys={} for i in xrange(len(nums)): if target-nums[i] in keys: return [keys[target-nums[i]],i] if nums[i] not in keys: keys[nums[i]]=i
二、三数之和
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res =[] lennums= len(nums) for i in range(lennums): left =i+1 right =lennums-1 if i>0 and nums[i-1]==nums[i]: left+=1 continue while left<right: sumthree = nums[i]+nums[left]+nums[right] if sumthree==0: res_col = [nums[i],nums[left],nums[right]] res.append(res_col) left+=1 right-=1 while nums[left]==nums[left-1] and left<right: left+=1 while nums[right]==nums[right+1] and left<right: right-=1 if sumthree<0: left+=1 if sumthree>0: right-=1 return res
最后
以上就是酷酷砖头最近收集整理的关于Leetcode——两数之和(twoSum)、三数之和(threeSum)——Python的全部内容,更多相关Leetcode——两数之和(twoSum)、三数之和(threeSum)——Python内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复