Leetcode:1-Two Sum
阿新 • • 發佈:2017-12-12
n) 一個 indices code dice ict cau nbsp hat
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
題意:找出數組num中的兩個數,它們的和為一個給定的數target,要求返回這兩個數的索引,已知只有一組解。
方法1:
復制數組num,對num的副本進行排序,然後設置頭尾指針遍歷num的副本找到符合要求的兩個數,再從原數組num中得到這兩個數的索引(找索引時一個從頭找,一個從尾找,防止找到同一個數)
1 ‘‘‘ 2 日期:2017-12-12 3 實現思路:先排序,再設置頭尾指針,從兩頭遍歷,直到相加等於target 4 ‘‘‘ 5 class Solution: 6 def twoSum(self, num, target): 7 numtosort=num[:] #復制num數組 8 numtosort.sort() #對復制的數組進行排序 9 i=0 #頭指針 10 j=len(numtosort) - 1 #尾指針 11 index = [] #存放索引 12 while i<j: 13 if numtosort[i]+numtosort[j]==target: #找到滿足條件的元素 14 for k in range(len(num)): #在原數組中找第一個元素的位置(從左往右遍歷) 15 if num[k]==numtosort[i]: 16 index.append(k) 17 break 18 for k in range((len(num)-1),-1,-1): #在原數組中找第二個元素的位置(從右往左遍歷) 19 if num[k]==numtosort[j]: 20 index.append(k) 21 break 22 index.sort() #將存放索引的list進行排序 23 break 24 elif numtosort[i]+numtosort[j]<target: #移動頭指針 25 i=i+1 26 elif numtosort[i]+numtosort[j]>target: #移動尾指針 27 j=j-1 28 return (index[0],index[1]) 29 30 if __name__==‘__main__‘: 31 num=[2,7,11,15] 32 target=9 33 solution=Solution() 34 print(solution.twoSum(num,target))
方法2:hash
1 ‘‘‘ 2 日期:2017-12-12 3 實現思路:hash。 4 時間復雜度:O(n) 5 ‘‘‘ 6 class Solution: 7 def twoSum(self,num,target): 8 d = {} #創建一個空dict 9 for i in range(len(num)): #遍歷num數組 10 x = num[i] #數組num的當前值 11 if target-x in d: #若另一個數已經存在於dict中,則兩個數都已找到,輸出即可 12 return (d[target-x],i) 13 d[x] = i #若另一個加數還沒在dict中,則將當前數存入dict中,其中數是key,索引是value 14 if __name__==‘__main__‘: 15 num=[7,11,15,2] 16 target=9 17 solution=Solution() 18 print(solution.twoSum(num,target))
Leetcode:1-Two Sum