两数交集
例如:
给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2]
答:
class Solution(object):
def intersect(self, nums1, nums2):
result=[]
dic = {}
for num in nums1:
if dic.has_key(num) == False:
dic[num] = 1
else:
dic[num] += 1
for num in nums2:
if dic.has_key(num) == True and dic[num]>0:
dic[num] -= 1
result.append(num)
return result
两数之和
示例:
给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]
class Solution(object):
def twoSum(self, nums, target):
arr = {}
for i in range(len(nums)):
if (target-nums[i]) in arr:
return [arr[target-nums[i]],i]
else:
arr[nums[i]]=i