本文主要是介绍【LeetCode算法练习(C++)】3Sum,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
链接:3Sum
解法:排序,之后拿出第一个数,转化为两数和问题,注意外层循环到倒数第三个数。时间O(n^2)
class Solution {
public:vector<vector<int> > threeSum(vector<int>& nums) {vector<int> numSet(3);vector< vector<int> > ans;sort(nums.begin(), nums.end());int sum;int len = nums.size();for(int i = 0; i < len - 2; i++) {sum = 0 - nums[i];numSet[0] = nums[i];for(int j = i + 1, k = len - 1; j < k;) {if(nums[j] + nums[k] == sum) {numSet[1] = nums[j++];numSet[2] = nums[k--];ans.push_back(numSet);while(j < k && nums[j] == nums[j-1]) j++;while(j < k && nums[k] == nums[k+1])k--;}else if(nums[j] + nums[k] < sum)j++;else k--;}while(i < len - 2 && nums[i + 1] == nums[i])i++;}return ans;}
};
Runtime: 109 ms
这篇关于【LeetCode算法练习(C++)】3Sum的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!