3SUM &&16. 3SUM closest && 18.4SUM

来源:互联网 发布:福建万照软件 编辑:程序博客网 时间:2024/05/14 07:17

3 sum closest就是3sum 的变形, 输出和target最相近的值

基本思路和3sum相同,但是添加了一个closedistance变量

public class Solution {    public int threeSumClosest(int[] nums, int target) {        if(nums.length<3||nums==null) return 0;        int res=0;        int closedistance=Integer.MAX_VALUE;        Arrays.sort(nums);                for(int k=0;k<nums.length-2;k++){            if(k==0||k>0 && nums[k]!=nums[k-1]){                int lo=k+1;                 int hi=nums.length-1;                while(lo<hi){                    int sum=nums[k]+nums[lo]+nums[hi];//must set here, because hi/lo changed the sum also changed, and we need to judge                    if(sum>target){                        if(sum-target<closedistance){                            closedistance=sum-target;                            res=sum;                        }                        hi--;                    }                    else if(sum<target){                        if(target-sum<closedistance){                            closedistance=target-sum;                            res=sum;                        }                        lo++;                    }                    else return sum;                }            }        }    return res;    }}

而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.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.A solution set is:[  [-1,  0, 0, 1],  [-2, -1, 1, 2],  [-2,  0, 0, 2]]
代码也很相似,利用3sum的思想,多一层循环 最终为O(N3)

public class Solution {    public List<List<Integer>> fourSum(int[] nums, int target) {        ArrayList<List<Integer>> ans = new ArrayList<List<Integer>>();        Arrays.sort(nums);        if(nums.length<4||nums==null) return ans;        if(4 * nums[0] > target || 4 * nums[nums.length - 1] < target) return ans;//这里要注意!!!避免TLE        for(int k=0;k<nums.length-3;k++){            if(k>0 && nums[k]==nums[k-1]) continue;            for(int i=k+1;i<nums.length-2;i++){                if(i>k+1 && nums[i]==nums[i-1]) continue;                int st=i+1; int ed=nums.length-1;                while(st<ed){                    int sum=nums[k]+nums[i]+nums[st]+nums[ed];                    if(sum==target){                        ans.add(Arrays.asList(nums[k],nums[i],nums[st],nums[ed]));                        while(st<ed && nums[st]==nums[st+1]) st++;                        while(st<ed && nums[ed]==nums[ed-1]) ed--;                        st++;                        ed--;                    }                    else if(sum>target) ed--;                    else st++;                }            }        }        return ans;    }}

都是套路。。






0 0
原创粉丝点击