本文主要是介绍LeetCode·15. 3Sum,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Given an array nums of n integers, are there elements a, b, c in nums 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.Example:Given array nums = [-1, 0, 1, 2, -1, -4],A solution set is:
[[-1, 0, 1],[-1, -1, 2]
]
思路:
2-sum问题基础上加一层循环
代码:
class Solution {
public:vector<vector<int>> threeSum(vector<int>& nums) {vector<vector<int>> vec;if(nums.size() == 0)return vec;sort(nums.begin(), nums.end());vector<int> v(3);int sum = 0;for(int i = 0; i < nums.size()-2; ++i){if(nums[i] > 0) return vec;sum = 0 - nums[i];v[0] = nums[i];for(int j = i+1, k = nums.size()-1; j <= k-1;){if(nums[j]+nums[k] == sum){v[1] = nums[j];v[2] = nums[k];vec.push_back(v);if(nums[j] != nums[k]){while((j < k) && nums[++j] == nums[j-1]){}while((j < k) && nums[--k] == nums[k+1]){}}else{break;}}else if(nums[j]+nums[k] < sum){++j;}else if(nums[j]+nums[k] > sum){--k;}}while(i < nums.size()-2 && nums[i+1] == nums[i])++i;}return vec;}
};
结果:
这篇关于LeetCode·15. 3Sum的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!