This is the python solution for the Leetcode problem – Two Sum – Leetcode Challenge – Python Solution.
Source – qiyuangong’s repository.
x
66
66
1
class Solution(object):
2
# def twoSum(self, nums, target):
3
# """
4
# :type nums: List[int]
5
# :type target: int
6
# :rtype: List[int]
7
# """
8
# #n^2
9
# ls = len(nums)
10
# for i in range(ls):
11
# for j in range(i + 1, ls):
12
# if nums[i] + nums[j] == target:
13
# return [i, j]
14
15
# def twoSum(self, nums, target):
16
# # hash 1
17
# hash_nums = {}
18
# for index, num in enumerate(nums):
19
# try:
20
# hash_nums[num].append(index)
21
# except KeyError:
22
# hash_nums[num] = [index]
23
# for index, num in enumerate(nums):
24
# another = target - num
25
# try:
26
# candicate = hash_nums[another]
27
# if another == num:
28
# if len(candicate) > 1:
29
# return candicate
30
# else:
31
# continue
32
# else:
33
# return [index, candicate[0]]
34
# except KeyError:
35
# pass
36
37
# def twoSum(self, nums, target):
38
# # hash 2
39
# hash_nums = {}
40
# for index, num in enumerate(nums):
41
# another = target - num
42
# try:
43
# hash_nums[another]
44
# return [hash_nums[another], index]
45
# except KeyError:
46
# hash_nums[num] = index
47
48
def twoSum(self, nums, target):
49
# two point
50
nums_index = [(v, index) for index, v in enumerate(nums)]
51
nums_index.sort()
52
begin, end = 0, len(nums) - 1
53
while begin < end:
54
curr = nums_index[begin][0] + nums_index[end][0]
55
if curr == target:
56
return [nums_index[begin][1], nums_index[end][1]]
57
elif curr < target:
58
begin += 1
59
else:
60
end -= 1
61
62
63
if __name__ == '__main__':
64
# begin
65
s = Solution()
66
print s.twoSum([3, 2, 4], 6)