原題地址:http://oj.leetcode.com/problems/two-sum/
題意:找出數組numbers中的兩個數,它們的和為給定的一個數target,並返回這兩個數的索引,注意這里的索引不是數組下標,而是數組下標加1。比如numbers={2,7,11,17}; target=9。那么返回一個元組(1,2)。這道題不需要去重,對於每一個target輸入,只有一組解,索引要按照大小順序排列。
解題思路:1,由於要找到符合題意的數組元素的下標,所以先要將原來的數組深拷貝一份,然后排序。
2,然后在排序后的數組中找兩個數使它們相加為target。這個思路比較明顯:使用兩個指針,一個指向頭,一個指向尾,兩個指針向中間移動並檢查兩個指針指向的數的和是否為target。如果找到了這兩個數,再將這兩個數在原數組中的位置找出來就可以了。
3,要注意的一點是:在原來數組中找下標時,需要一個從頭找,一個從尾找,要不無法通過。如這個例子:numbers=[0,1,2,0]; target=0。如果都從頭開始找,就會有問題。
代碼:
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): index = [] numtosort = num[:]; numtosort.sort() i = 0; j = len(numtosort) - 1 while i < j: if numtosort[i] + numtosort[j] == target: for k in range(0,len(num)): if num[k] == numtosort[i]: index.append(k) break for k in range(len(num)-1,-1,-1): if num[k] == numtosort[j]: index.append(k) break index.sort() break elif numtosort[i] + numtosort[j] < target: i = i + 1 elif numtosort[i] + numtosort[j] > target: j = j - 1 return (index[0]+1,index[1]+1)
以上代碼太冗長了,如果使用dict也就是哈希,就會簡潔很多。
class Solution: # @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