leetcode -18 4Sum

来源:互联网 发布:微道网络推广shero877 编辑:程序博客网 时间:2024/05/20 08:26

4Sum

 

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

 

给定一个数组S里包含n个整数,给定一个整数target,从S中找出4个数字,这4个数组满足条件:它们的和在数轴上与target最短。最后返回它们的和。

 

 

分析:

         第一种想法就是将之前的3sumCloest为基础,只需要把先选定一个值a,下边为i,然后就变成了在S[i]到S[end](end代表S数组中最后元素的下标)中找到target1 = target – a 的值,奠定在3sum的基础上,需要多遍历一次S,所以最终的结果就是O(n^3)。

 

         不难看出来ksum的复杂度就为O(n^k-1)

 PS:附上3Sumclosest的文章。

http://blog.csdn.net/laeen/article/details/54629503

 

附上3sum的算法思想:

算法思想:

 

1.  首先将数组进行排序。

2.  从第一个下标开始,遍历数组,以当前访问到的数组元素作为一个轴值,其下标为i。

3.  固定一个轴值,然后选取从当前轴值的后一位元素,下标为j = i + 1,和数组的最后一个元素,下标为k = S.size - 1,进行向中间靠拢。靠拢的规则是,若S[i] + S[j] + S[k]到target的差,大于0,就移动k,减小S[k]的值;若小于0,移动j,增加S[j]的值。

若等于0,就直接返回结果。

 

 

 

vector< vector<int> > r;vector<int> temp ;int now;//当前遍历到的值void threeSum(vector<int>& num, int target,int startindex,int endindex)  {int j,k;//j,k分别为数组两头移动的下标,用来进行遍历 for (int i = startindex; i < endindex; i++) {if (i > startindex && num[i] == num[i - 1])//避免重复的计算     continue ;    j = i + 1;k = endindex;while (j < k) {if (j > i + 1 && num[j] == num[j - 1]) {++j;continue ;}int sum = num[i] + num[j] + num[k];if (sum == target) {temp.clear();temp.push_back(now);temp.push_back(num[i]);temp.push_back(num[j]);temp.push_back(num[k]);r.push_back(temp);++j;}else if (sum > target) {--k;} //sum > 0else {++j;} //sum < 0} // while (i < k)} // for (int i)    }    vector< vector<int> > fourSum(vector<int>& nums, int target) {sort(nums.begin(), nums.end());int endindex = nums.size() - 1;for(int i = 0 ; i <= endindex ; i++){if (i > 0 && num[i] == num[i - 1])//避免重复的计算     continue ;now = nums[i];int target1 = target - now;threeSum(nums, target1,i + 1,endindex);}        return r;    }

 

 

0 0
原创粉丝点击