Tag: Dict
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic={}
ret=[]
for i in range(len(nums)):
if dic.has_key(nums[i]):
ret.append(dic[nums[i]])
ret.append(i)
break
dic[target-nums[i]]=i
return ret
complexity analysis:
3 sum
find 3 number in the given list, and the sum of them is 0
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
num.sort()
ans = []
target = 0
for i in range(0, len(num)):
if (i > 0 and num[i] == num[i-1]): continue # only reserve first of all same values
l, r = i + 1, len(num) - 1
while l < r:
sum = num[i] + num[l] + num[r]
if sum == target:
ans.append([num[i], num[l], num[r]])
while l < r and num[l] == num[l + 1]: l = l + 1 # remove duplicate
while l < r and num[r] == num[r - 1]: r = r - 1 # remove duplicate
l, r = l + 1, r - 1
elif sum < target:
l = l + 1
else:
r = r - 1
return ans
[16] 3sum closet
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
mindiff=sys.maxint
ret=0
for i in range(len(nums)-2):
left=i+1
right=len(nums)-1
while left<right:
sumall=nums[i]+nums[left]+nums[right]
diff=abs(target-sumall)
if diff<mindiff:
mindiff=diff
ret=sumall
if sumall<target:
left=left+1
elif sumall>target:
right=right-1
else:
return sumall
return ret
18. 4Sum
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
使用双指针进行遍历
#
# @lc app=leetcode id=18 lang=python
#
# [18] 4Sum
#
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
if len(nums)<4:
return []
ret=[]
nums=sorted(nums)
for i in range(len(nums)-3):
if i>0 and nums[i]==nums[i-1]:
continue
t3=target-nums[i]
for j in range(i+1,len(nums)-2):
if j>i+1 and nums[j]==nums[j-1]:
continue
t2=t3-nums[j]
l=j+1
r=len(nums)-1
while l<r:
if (nums[l]+nums[r])==t2:
ret.append([nums[i],nums[j],nums[l],nums[r]])
while l<r and nums[r]==nums[r-1]:
r=r-1
while l<r and nums[l]==nums[l+1]:
l=l+1
l=l+1
r=r-1
elif (nums[l]+nums[r])>t2:
r=r-1
else:
l=l+1
return ret