zoukankan      html  css  js  c++  java
  • [leetcode]3Sum Closest

    至此,终于把LeetCode Old OJ里的132题刷完了,小小的成就。

    此题算法简单,就是O(n^2),采用和Two Sum类似的做法就是了。我的代码略有麻烦之处,主要是在函数里判断了一次abs的差值,外面又判断了一次,但总体不影响。

    注意,先选定i,然后在i后面的元素做TwoSum,意思是当第一个元素是i时的结果,这样就不会重复。

    也有不需要子函数的写法,更简洁:http://www.cnblogs.com/graph/p/3343847.html

    public class Solution {
        public int threeSumClosest(int[] num, int target) {
            Arrays.sort(num);
            int len = num.length;
            int diff = target - (num[0] + num[1] + num[2]);
            for (int i = 0; i < len - 2; i++)
            {
                int tmp = twoSumClosest(num, target - num[i], i + 1);
                if (tmp == 0) return target;
                if (Math.abs(tmp) < Math.abs(diff))
                {
                    diff = tmp;
                }
            }
            return target - diff;
        }
        
        private int twoSumClosest(int[] num, int target, int l)
        {
            int r = num.length - 1;
            int diff = target - num[l] - num[r];
            while (l < r)
            {
                int sum = num[l] + num[r];
                if (sum == target)
                {
                    return 0;
                }
                else
                {
                    int tmp = target - num[l] - num[r];
                    if (Math.abs(tmp) < Math.abs(diff))
                    {
                        diff = tmp;
                    }
                    if (sum > target)
                    {
                        r--;
                    }
                    else
                    {
                        l++;
                    }
                }
            }
            return diff;
        }
    }
    

      

  • 相关阅读:
    Sublime Text 3——插件配置篇
    Sublime Text 3——基本介绍篇
    线性同余方程
    费马小定理
    一点心事
    寒诗
    e网通学习笔记
    std::cout<<"Goodbye 2019"<<" "<<"Hello 2020"<<' ';
    新砍
    NOIP2019游记
  • 原文地址:https://www.cnblogs.com/lautsie/p/3356295.html
Copyright © 2011-2022 走看看