[LeetCode]Two Sum
今晚再刷一题,题目如下:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
第一想法,遍历,如果numbers有n个,第1个和2,3,4,...,n比较,第2个和3,4,5,...,n比较,...,第n-1个和n个比较,当然遇到符合的就退出,复杂度O(n^2)。
立刻意识到不需要遍历,应该用查找,遍历numbers[i]查找numbers里是否有numbers[i]-target,有则退出,否则遍历numbers[i+1].可以自己实现一个简单的平衡二叉查找树,不过直接利用map更方便,key是number。val是index。可是map的key必须是唯一的,numbers有可能有相同的数,从题目中You may assume that each input would have exactly one solution.可以推断,numbers中相同的数最多只可能有2个,所以可以把key改为number*2,遇到重复的,第二个把key记为number*2+1,但这样有个风险,输入的int型有可能溢出,提交尝试了一下,AC。结果的代码如下:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { map<int, int> num2index; int n = numbers.size(); vector<int> indexs(2, 0); for (int i = 0; i < n; ++i) { int current = numbers[i]; if (num2index.find(current<<1)==num2index.end()) { num2index[current<<1] = i+1; } else { num2index[(current<<1)+1] = i+1; } } for (auto it = num2index.begin(); it != num2index.end(); ++it) { int current = (it->first)>>1; int left = target - current; if (left!=current && num2index.find(left<<1) != num2index.end()) { indexs[0] = it->second; indexs[1] = num2index[left<<1]; break; } if (left == current && num2index.find(left<<1) != num2index.end()) { if (it->second != num2index[left<<1]) { indexs[0] = it->second; indexs[1] = num2index[left<<1]; } else { indexs[0] = it->second; indexs[1] = num2index[(left<<1)+1]; } break; } } if (indexs[1]<indexs[0]) { int tmp = indexs[0]; indexs[0] = indexs[1]; indexs[1] = tmp; } return indexs; } };
看了一下Dicuss,有牛人的解答,是边构造map边判断,就不需要担心key相同了,思路更清晰,效率更高,且不存在担心int溢出,Java代码如下:
public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) { result[1] = i + 1; result[0] = map.get(target - numbers[i]); return result; } map.put(numbers[i], i + 1); } return result; }