【LeetCode】15. 3Sum

  • 2019 年 11 月 8 日
  • 筆記

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/shiliang97/article/details/102315528

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] ]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {  public:      vector<vector<int>> threeSum(vector<int>& nums) {          sort(nums.begin(),nums.end());          vector<vector<int>> ans;          int l,r,n;          for(int k=0;k<nums.size()-3;k++){              l=k+1;              r=nums.size()-1;              while(r<l){                  n=nums[k]+nums[l]+nums[r];                  if(n==0){                      vector<int> temp;                      temp.push_back(nums[k]);                      temp.push_back(nums[l]);                      temp.push_back(nums[r]);                      ans.push_back(temp);                      l++;                      r--;                  }else if(n<0){                      l++;                  }else if(n>0){                      r--;                  }              }          }          return ans;      }  };