http://oj.leetcode.com/problems/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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
是个比较经典的题目。
如果不考虑时间复杂度,那直接遍历整个数组,对于第一个元素遍历之后的所有元素,以此类推。时间复杂度是O(n^2)
显然这样不是一个明智的选择。
如果我们先用排序,然后左右各放置一个指针,求其加和,如果大于则右指针向左,如果小于目标则左指针向右。如果解唯一,则必然可以得到正确的答案,然后返回下标即可,时间复杂度是O(nlogn) 就是排序的时间复杂度。
还有更快的方法,如果采用哈希表进行储存,比如说,用python的字典,key为原先数组的数值,value为数组的索引,对于一个元素x直接寻找destination-x的key,找到以后直接返回value就是下标。因为哈希表的查找是O(1)的,所以时间复杂度为O(n)