-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ1.py
More file actions
34 lines (31 loc) · 1.01 KB
/
Q1.py
File metadata and controls
34 lines (31 loc) · 1.01 KB
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
32
33
34
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
sortedNumId = sorted(range(len(nums)),key=lambda k:nums[k])
tail = len(nums)
head = 0
while(tail>=head):
if nums[sortedNumId[head]]+nums[sortedNumId[tail-1]]==target:
break
elif nums[sortedNumId[head]]+nums[sortedNumId[tail-1]]>target:
tail-=1
else:
head+=1
return [sortedNumId[head],sortedNumId[tail-1]]
def twoSum(self,nums,target):
hashmap = {}
for index,num in enumerate(nums):
anotherNum = target - num
if anotherNum in hashmap:
return [hashmap[anotherNum],index]
hashmap[num] = index
return None
if __name__ == '__main__':
testList =[3,2,4]
target = 6
test = Solution()
print(test.twoSum(testList,target))