zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    OpenGL 五
    OpenGL 四
    对UICollectionView的学习
    KVO的简单用法
    css在各浏览器中的兼容问题
    iOS学习笔记---网络请求
    UI学习笔记---第十六天XML JSON解析
    ui学习笔记---第十五天数据库
    UI学习笔记---第十四天数据持久化
    UI学习笔记---第十三天可视化设计 XIB, StoryBoard
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5161386.html
Copyright © 2011-2022 走看看