3SumCloset

来源:互联网 发布:新代数控车床编程实例 编辑:程序博客网 时间:2024/06/07 22:26

原题:

Given an array S of n integers, are there elements a,b, c in S 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.

For example, given array S = [-1, 0, 1, 2, -1, -4],A solution set is:[  [-1, 0, 1],  [-1, -1, 2]]

即从给定数组中找到三个数字和和给定的target最接近。


思路过程&解题思路:

和3Sum思路一样,用双指针,同时找一个变量存储所有遍历过的三个数和target差的绝对值的最小值,最后用targ加这个变量就好了。第二次提交代码就acceptance了。

时间复杂度o(n^2)


结果代码:

public int threeSumClosest(int[] nums, int target) {    Arrays.sort(nums);    int dif = nums[0] + nums[1] + nums[2] - target;//初始化dif,target + dif就是最后返回结果    for (int i = 0;i < nums.length;i++){        int l = i + 1,r = nums.length - 1;        while (l < r){            int sum = nums[i] + nums[l] + nums[r];            dif = (Math.abs(dif) < Math.abs(sum - target))?  dif : (sum - target);            if (sum > target) r--;            if (sum < target) l++;            if (sum == target) return target;        }    }return target + dif;}

原创粉丝点击