16. 3Sum Closest(medium)

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

分析:

从一个整形数组中找出三个数字之和最接近目标值。
和上一个题类似,遍历数组,找到与目标值距离最小的三个数之和。时间复杂度O(n^2)。

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

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,199评论 0 10
  • 谁能够准确get到每一个让人怦然心动的点,谁给营造一种被爱的幻觉,而且像初恋般甜蜜。 大家都在说宋仲基欧巴的撩妹大...
    家靠海边喜欢浪阅读 2,622评论 0 1
  • 今天是2018年最后一个工作日,我校组织实施2018年瑞金市教师培训最后一个项目——特殊教育“送教上门”教师培训。...
    幸运杏阅读 5,375评论 0 8
  • 晦涩的冬天,暗沉的乌云夹杂着凶猛地西风,四处都是飞舞的叶子。 而我身边的木槿上,有一片泛黄的叶也摇摇晃晃,无论风怎...
    青鸟爱吃鱼阅读 3,265评论 0 2

友情链接更多精彩内容