3Sum Closest

题目
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.

答案

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int mindiff = Integer.MAX_VALUE;
        int ans = 0;
        for(int k = 0; k < nums.length - 2; k++) {
            int i = k + 1;
            int j = nums.length - 1;
            int find = target - nums[k];
            while(i < j) {
                if(Math.abs(nums[i] + nums[j] - find) < mindiff) {
                    mindiff = Math.abs(nums[i] + nums[j] - find);
                    ans = nums[i] + nums[j] + nums[k];
                }
                else if(nums[i]+ nums[j] < find) i++;
                else j--;
            }
        }
        return ans;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,948评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,547评论 0 23
  • 起雾了,浓浓的雾由海上飘来,远处船舶的灯光,像幽灵一样摇曳不定。大雾掩盖了城市的霓虹灯,那明亮多彩的灯光,变成鬼火...
    smile丝唛小主阅读 417评论 0 0

友情链接更多精彩内容