3Sum
Posted dylqt
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3Sum相关的知识,希望对你有一定的参考价值。
1、Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
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>& nums) { vector<vector<int>> triples; sort(nums.begin(), nums.end()); int i = 0, last = nums.size() - 1; while (i < last) { int a = nums[i], j = i+1, k = last; // 先选中一个,然后后面的找两个值 while (j < k) { int b = nums[j], c = nums[k], sum = a+b+c; if (sum == 0) triples.push_back({a, b, c}); // 使用了vector的初始化{a, b, c} if (sum <= 0) while (nums[j] == b && j < k) j++; // 这个厉害,可以使用在判断相等的时候一直往前 if (sum >= 0) while (nums[k] == c && j < k) k--; } while (nums[i] == a && i < last) i++; } return triples; } };
以上是关于3Sum的主要内容,如果未能解决你的问题,请参考以下文章