leetcode之3Sum

来源:互联网 发布:知乎三大程序员 编辑:程序博客网 时间:2024/04/30 06:53

原题如下:

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • 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)
经过昨天的搜狗面试,我更加注意算法的时间复杂度问题,显然这道题存在暴力解法,其复杂度为O(n*n*n),现在考虑的是降低复杂度的问题,首先进行排序,其时间复杂度为O(nlogn),然后当为2Sum问题时可以采用左右指针查找的方法(这里因为数组中存在重复元素,所以需要去重),此时查找复杂度为O(n),所以总的时间复杂度为O(nlogn),在求解3Sum问题时,首先选中一个元素,然后在剩余的元素中进行2Sum的查找,此时总的时间复杂度为O(n*n),这里需要注意的仍是去重问题,首先选择第一个元素时需要去重,接下来在左右指针移动过程中仍要去重。

class Solution {public:    vector<vector<int> > threeSum(vector<int> &num) {sort(num.begin(),num.end());vector<vector<int>>vv;if(num.size() < 3)return vv;for(int i = 0; i < num.size() - 2; i++){if(i > 0 && num[i] == num[i - 1])continue;twoSum(vv,num,i + 1,num[i] * -1);}return vv;    }void twoSum(vector<vector<int>>&vv,vector<int>num,int index,int target){int left = index,right = num.size() - 1;while(left < right){int temp = num[left] + num[right];if(temp == target ){    vector<int>triplet;triplet.push_back(target * -1);triplet.push_back(num[left]);triplet.push_back(num[right]);vv.push_back(triplet);left++;right--;while ( left < num.size() && num[left] == num[left - 1] )left++;while( right >= 0 && num[right] == num[right + 1])right--;}else if(temp > target){    right--;}elseleft++;}}};


0 0
原创粉丝点击