zoukankan      html  css  js  c++  java
  • [leetcode] 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).

    https://oj.leetcode.com/problems/3sum-closest/

    思路1:类似3Sum,区别是不需要去重,另外需要维护一个最小差值。

    import java.util.Arrays;
    
    public class Solution {
    	public int threeSumClosest(int[] num, int target) {
    		int n = num.length;
    		Arrays.sort(num);
    		int min = Integer.MAX_VALUE;
    		int result = 0;
    		for (int i = 0; i < n; i++) {
    			int start = i + 1, end = n - 1;
    			int sum = target - num[i];
    			int cur = 0;
    			while (start < end) {
    				cur = num[start] + num[end];
    				if (Math.abs(cur + num[i] - target) < min) {
    					min = Math.abs(cur + num[i] - target);
    					result = cur + num[i];
    				}
    				if (cur < sum)
    					start++;
    				else if (cur > sum)
    					end--;
    				else {
    					start++;
    					end--;
    				}
    			}
    		}
    		return result;
    	}
    
    	public static void main(String[] args) {
    		System.out.println(new Solution().threeSumClosest(new int[] { -1, 2, 1,
    				-4 }, 1));
    		System.out.println(new Solution().threeSumClosest(
    				new int[] { 1, 2, 3, }, 100));
    	}
    }

    第二遍记录:

      Math.abs别忘记了。

    public class Solution {
        public int threeSumClosest(int[] num, int target) {
            int n =num.length;
            Arrays.sort(num);
            int min = Integer.MAX_VALUE;
            int res=0;
            
            for(int i=0;i<n;i++){
                int start=i+1;
                int end =n-1;
                int sum = target - num[i];
                while(start<end){
                    if(Math.abs(num[start]+num[end]+num[i]-target)<min){
                        min=Math.abs(num[start]+num[end]+num[i]-target);
                        res=num[start]+num[end]+num[i];
                    }
                    
                    if(num[start]+num[end]<sum)
                        start++;
                    else if(num[start]+num[end]>sum)
                        end--;
                    else{
                        start++;
                        end--;
                    }
                    
                    
                }
                
            }
            return res;
        }
    }
  • 相关阅读:
    贝叶斯定理
    用matplotlib统计数据并画图
    词云图
    一行python代码能写出啥?
    用python生成二维码
    18个python的高效编程技巧
    django简介
    vue点击变色
    selenium破解人人登陆验证码
    selenium请求豆瓣网
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3810695.html
Copyright © 2011-2022 走看看