當前位置:
首頁 >
算法--三数之和
發布時間:2025/6/15
24
豆豆
??強烈推薦人工智能學習網站??? ? ??
給你一個包含 n 個整數的數組?nums,判斷?nums?中是否存在三個元素 a,b,c ,使得?a + b + c = 0 ?請你找出所有滿足條件且不重復的三元組。
注意:答案中不可以包含重復的三元組。
示例:
給定數組 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) {// 需要和上一次枚舉的數不相同,數組里面有相同的元素if (first > 0 && nums[first] == nums[first - 1]) {continue;}// c 對應的指針初始指向數組的最右端int third = n - 1;int target = -nums[first];// 枚舉 bfor (int second = first + 1; second < n; ++second) {// 需要和上一次枚舉的數不相同,數組里面有相同的元素if (second > first + 1 && nums[second] == nums[second - 1]) {continue;}// 需要保證 b 的指針在 c 的指針的左側while (second < third && nums[second] + nums[third] > target) {--third;}// 如果指針重合,隨著 b 后續的增加// 就不會有滿足 a+b+c=0 并且 b<c 的 c 了,可以退出循環if (second == third) {break;}if (nums[second] + nums[third] == target) {ans.push_back({nums[first], nums[second], nums[third]});}}}return ans;} };target 是需要固定的數,如果target為-3,那只需要second+third=3就符合結果,second是左邊的指針,third是右邊的指針。因為整個數組是升序的,如果second+third>3,這說明合大了,所有third指針需要移動;如果second+third<3,則second指針需要移動。
?
?
參考地址:https://leetcode-cn.com/problems/3sum/solution/san-shu-zhi-he-by-leetcode-solution/
?
總結
- 上一篇: 动态拼接字符串
- 下一篇: 代码大全--防御试编程