• LeetCode(16):3Sum Closest


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

    题意:给定一个数组和目标元素,找出数组中的3个元素使其和最接近目标元素。

    思路:首先对给定的数组进行排序,然后从0到数组元素长度len-2开始循环,对于每层循环,定义两个指针一个left指向i+1,right指向数组的尾部,然后开始判断i,left和start指向的元素之和是否更接近给定的元素,如果接近则更新,然后判断3个元素的和是大于给定的元素还是小于给定的元素,大于的话left指针加1,小于的话right指针减1;

    代码:

    public int threeSumClosest(int[] nums, int target) {
            int closest = nums[0] + nums[1] + nums[2];
            int diff = Math.abs(closest - target);
            Arrays.sort(nums);
            for (int i = 0; i < nums.length - 2; i++) {
                int start = i + 1;
                int end = nums.length - 1;
                while (start < end) {
                    int sum = nums[i] + nums[start] + nums[end];
                    int newDiff = Math.abs(sum - target);
                    if (newDiff < diff) {
                        diff = newDiff;
                        closest = sum;
                    }
                    if (sum < target)
                        start++;
                    else
                        end--;
                }
            }
            return closest;
        }
  • 相关阅读:
    CAP概述与技术选型
    maven基础命令
    那就从头开始吧,哈哈。
    react 小细节
    二分查找法,折半查找原理
    心态很重要
    apache 软件基金会分发目录。
    jquery的基础知识复习()
    jquery的基础知识复习(基础选择器,属性选择器,层级选择器)
    CPP函数类型转换
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5161386.html
Copyright © 2020-2023  润新知