leetCode之Two Sum python實現
阿新 • • 發佈:2019-02-13
1. Two Sum
- 要求:
Given an array of integers, return indices of the two numbers such that they add up to a specific target。
You may assume that each input would have exactly one solution, and you may not use the same element twice. - 題目大意:給定一個整數陣列,返回其中兩個數相加等於目標值的那兩個數的索引。你可以假設只有唯一的兩個數相加等於目標值。不允許你使用同一個數兩次。
1.1 暴力法
- 解題思路:直接定義兩個指標,從頭開始窮舉搜尋。
- 時間複雜度為O(n2)。
- 這種結果在leetCode是通不過的,會產生“Time Limit Exceeded”。
- 程式如下
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
'''
Time Limit Exceeded
'''
index = []
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
index.append(i)
index.append(j)
return index
1.2 排序後首尾同時遍歷(不專業,暫且就這麼叫吧。。。)
- 解題思路:首先對陣列進行升冪排序,然後定義兩個指標left和right,分別從左和從右開始遍歷。因為排序後,陣列是從小到大排列的,所以如果nums[left] + num[right] > target,那麼right左移,反之left右移。當找到兩個數時,再確定這兩個數在原陣列中的位置即可。
- 時間複雜度:O(n+n+n+n)=O(n)。
- 執行結果:耗時66ms
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp_num = nums[:] # [:]表示深拷貝,a = b 表示淺拷貝
temp_num.sort() # sort會改變原來陣列,所以上面要深複製
i = 0
j = len(temp_num) - 1
index = []
while i < j:
if temp_num[i] + temp_num[j] == target:
for n in range(0,len(nums)):
if temp_num[i] == nums[n]:
index.append(n)
break
for m in range(len(nums)-1,-1,-1):
if temp_num[j] == nums[m]:
index.append(m)
break
index.sort()
break
elif temp_num[i] + temp_num[j] > target:
j -= 1
elif temp_num[i] + temp_num[j] < target:
i += 1
return index
1.3 雜湊法
- 解題思路:第2種方法寫的太麻煩了,可以使用使用python中dict,也就是hashmap。
- 時間複雜度:O(n)
- 執行結果:耗時53ms
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
index = 0
for i in range(len(nums)):
if target - nums[i] in dict:
return [dict[target - nums[i]],i]
else:
dict[nums[i]] = index
index += 1