算法--三数之和
??強(qiáng)烈推薦人工智能學(xué)習(xí)網(wǎng)站??? ? ??
給你一個包含 n 個整數(shù)的數(shù)組?nums,判斷?nums?中是否存在三個元素 a,b,c ,使得?a + b + c = 0 ?請你找出所有滿足條件且不重復(fù)的三元組。
注意:答案中不可以包含重復(fù)的三元組。
示例:
給定數(shù)組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
? [-1, 0, 1],
? [-1, -1, 2]
]
解題思路:排序+雙指針
class Solution { public:vector<vector<int>> threeSum(vector<int>& nums) {int n = nums.size();sort(nums.begin(), nums.end());vector<vector<int>> ans;// 枚舉 afor (int first = 0; first < n; ++first) {// 需要和上一次枚舉的數(shù)不相同,數(shù)組里面有相同的元素if (first > 0 && nums[first] == nums[first - 1]) {continue;}// c 對應(yīng)的指針初始指向數(shù)組的最右端int third = n - 1;int target = -nums[first];// 枚舉 bfor (int second = first + 1; second < n; ++second) {// 需要和上一次枚舉的數(shù)不相同,數(shù)組里面有相同的元素if (second > first + 1 && nums[second] == nums[second - 1]) {continue;}// 需要保證 b 的指針在 c 的指針的左側(cè)while (second < third && nums[second] + nums[third] > target) {--third;}// 如果指針重合,隨著 b 后續(xù)的增加// 就不會有滿足 a+b+c=0 并且 b<c 的 c 了,可以退出循環(huán)if (second == third) {break;}if (nums[second] + nums[third] == target) {ans.push_back({nums[first], nums[second], nums[third]});}}}return ans;} };target 是需要固定的數(shù),如果target為-3,那只需要second+third=3就符合結(jié)果,second是左邊的指針,third是右邊的指針。因?yàn)檎麄€數(shù)組是升序的,如果second+third>3,這說明合大了,所有third指針需要移動;如果second+third<3,則second指針需要移動。
?
?
參考地址:https://leetcode-cn.com/problems/3sum/solution/san-shu-zhi-he-by-leetcode-solution/
?
總結(jié)
- 上一篇: 动态拼接字符串
- 下一篇: 代码大全--防御试编程