LeetCode/Python: 1 Two Sum
Posted lijinghuabj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode/Python: 1 Two Sum相关的知识,希望对你有一定的参考价值。
1. Method1
class Solution(object):
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
d = {}
for i, e in enumerate(num):
if e in d:
return d[e] + 1, i + 1
d[target - e] = i
s = Solution()
print (s.twoSum([0, 2, 1,0], 0))
print (s.twoSum([2,4,6],6))
Result:
(1, 4) (1, 2)
2. Method2- TBD
xrange=range class Solution(object): # @return a tuple, (index1, index2) def twoSum(self, num, target): dict = {} for i in xrange(len(num)): x = num[i] if target-x in dict: return (dict[target-x]+1, i+1) dict[x] = i s = Solution() print (s.twoSum([3, 2, 4], 6))
Result:
(2, 3)
3. Method3 - TBD
class Solution(object): def twoSum(self, nums, target): # two point nums_index = [(v, index) for index, v in enumerate(nums)] nums_index.sort() begin, end = 0, len(nums) - 1 while begin < end: curr = nums_index[begin][0] + nums_index[end][0] if curr == target: return [nums_index[begin][1], nums_index[end][1]] elif curr < target: begin += 1 else: end -= 1 if __name__ == ‘__main__‘: # begin s = Solution() print (s.twoSum([0, 1, 2, 0], 0))
Result:
以上是关于LeetCode/Python: 1 Two Sum的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode][Python]Intersection of Two Arrays
[LeetCode][Python]Intersection of Two Arrays II
Leetcode 167Two Sum II - Input array is sorted