leetcode 16. 3Sum Closest

来源:互联网 发布:知尖品牌 编辑:程序博客网 时间:2024/05/01 14:45
import java.util.Arrays;//Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. //Return the sum of the three integers. You may assume that each input would have exactly one solution.//For example, given array S = {-1 2 1 -4}, and target = 1.//The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).public class Solution {public static void main(String[] args) {int[] a = {1,1,1,1};int result = threeSumClosest(a,-100);System.out.println(result);}public static int threeSumClosest(int[] nums, int target) {        int result = 0;        int cha = 1000;        Arrays.sort(nums);//先对数组排序        for(int i = 0;i<nums.length-2;i++){//与上一题差不多,遍历数组,从当前元素之后的元素段首尾相加:1(当前),1(首),1,1(尾)        int j = i+1;        int end = nums.length-1;        while(j<end){//首小于尾时循环        if(nums[i]+nums[j]+nums[end] == target){        return target;        }else if(nums[i]+nums[j]+nums[end]<target){//根据三数相加与target的差值调整首尾的位置        if(cha>Math.abs(target-nums[i]-nums[j]-nums[end])){        cha = Math.abs(target-nums[i]-nums[j]-nums[end]);        result = nums[i]+nums[j]+nums[end];        }        j++;        }else{        if(cha>Math.abs(target-nums[i]-nums[j]-nums[end])){        cha = Math.abs(target-nums[i]-nums[j]-nums[end]);        result = nums[i]+nums[j]+nums[end];        }        end--;        }        }        }        return result;    }}

0 0
原创粉丝点击