标签:algorithm leetcode c++ hash
题目:给定一个数组,以及一个 target 值,target 表示目标和,要求在数组中找到两个数,xi,xj,使得 xi + xj = target。返回值是找到的两个数的下标索引,升序排序。假定至少存在一对解。
分析:对于要处理数组的问题,我们的理想状态都是给定的数组是有序的就好了,在有序后,我们就可以首位各放一个标记。类似于二分查找。
vector<int> twoSum(vector<int> &numbers, int target){ vector<int> re; if(numbers.size() == 0) return re; sort(numbers.begin(), numbers.end()); int small = 0; int large = numbers.size() - 1; while (small < large) { int sum = numbers[small] + numbers[large]; if(sum == target) { re.push_back(small + 1); re.push_back(large + 1); return re; } else if(sum < target) ++small; else --large; } return re; }
既然要求值本身与下标对应,就选择map来存储,要速度,就hash,所以最后选hash_map来存储信息。这样的时间复杂度可以在O(N).
vector<int> twoSum2(vector<int> &numbers, int target){ vector<int> re; if(numbers.size() == 0) return re; unordered_map<int, int> value_index_map, value_index_multi_map; for (int i = 0; i < numbers.size(); ++i) { unordered_map<int, int>::iterator ifind = value_index_map.find(numbers[i]); //exited value if(ifind != value_index_map.end()){ //get the result or not if( numbers[i] * 2 == target) { re.push_back(ifind->second); re.push_back(i + 1); return re; } } //new value else{ //find the opposite part ifind = value_index_map.find(target - numbers[i]); if(ifind != value_index_map.end()) { re.push_back(ifind->second); re.push_back(i + 1); return re; } //add the new one. else value_index_map[numbers[i]] = i + 1; } } return re; }
[leetcode]:Two Sum,布布扣,bubuko.com
标签:algorithm leetcode c++ hash
原文地址:http://blog.csdn.net/shiquxinkong/article/details/25959261