1.2sum问题
Given nums = [2, 7, 2, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
方法:排序,使用左右指针,复杂度为nlogn
class Solution { public: vector<int> TwoSum(vector<int> &a, int num) { vector<int> result; sort(a.begin(), a.end());//vector中sort函数使用的是快排,时间复杂度为NlogN int len = a.size(); int low = 0; int high = len - 1; while (low < high) { if (low == high) break; int sum = a[low] + a[high]; if (sum < num) low++; else if (sum > num) high--; else { result.push_back(a[low]); result.push_back(a[high]); low++; high--; } } for (int i = 0; i < result.size(); i++) { cout << result[i] << endl; } return result; } }; int main() { Solution st; vector<int> a = {2, 5, 3, 6, 1}; st.TwoSum(a, 7); }
2.3Sum问题
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:[ [-1, 0, 1], [-1, -1, 2]]。
方法
class Solution { public: vector<vector<int>> ThreeSum(vector<int> &a) { vector<vector<int>> result; sort(a.begin(), a.end()); int len = a.size(); for (int i = 0; i < len; i++) { int target = -a[i];//对当前数取相反数 int low = i + 1; int high = len - 1; while (low < high) { if (low == high) break; int sum = a[low] + a[high]; if (sum > target) high--; else if (sum < target) low++; else { vector<int> tmp(3, 0); tmp[0] = a[i]; tmp[1] = a[low]; tmp[2] = a[high]; result.push_back(tmp); while (low < high && a[low] == tmp[1])//去除重复元素 low++; while (low < high && a[low] == tmp[2]) high--; } } while (i + 1 < len && a[i + 1] == a[i])//若相邻两数相等,可跳过后面那个数 i++; } return result; } };