标签:
首先作这个题,最直接的思路是两个for循环,然而所带来的缺陷是时间复杂度太高O(n2)。所以要转变思路:如何能一次遍历就解决问题?
因为是两个数相加来得到一个既定的数(target),那就有一个思路是:能不能两头相加,然后通过头指针和尾指针来回向中间靠拢来实现?
答案是可以的。分两步走:
注意事项:
语法细节:
代码实现:
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): numtosort = num[:] numtosort.sort() i = 0 j = self.search(numtosort,target) while(i < j): if(numtosort[i] + numtosort[j] == target): be = self.before_search(num,numtosort,i) af = self.after_search(num,numtosort,j) if be < af: return (be,af) else: return (af,be) elif(numtosort[i] + numtosort[j] < target): i = i + 1 else: j = j - 1 def search(self,numtosort,target): for i in range(0,len(numtosort)): if numtosort[len(numtosort)-i-1] <= target: if i == 0: return len(numtosort)-1 else: return len(numtosort)-i def before_search(self,num,numtosort,number): for i in range(0,len(num)): if(num[i] == numtosort[number]): return i+1 def after_search(self,num,numtosort,number): for i in range(0,len(num)): if(num[len(num)-i-1] == numtosort[number]): return len(num)-i if __name__ == ‘__main__‘: num = [-3,4,3,90] target = 0 solution = Solution() print solution.twoSum(num,target)
标签:
原文地址:http://www.cnblogs.com/tosouth/p/4268245.html