zoukankan      html  css  js  c++  java
  • leetcode 16:最接近的三数之和

    import java.util.Arrays;
    
    /**
     * @Class ThreeSumClosest
     * @Description 16. 最接近的三数之和
     * 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,
     * 使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
     * <p>
     * 示例:
     * 输入:nums = [-4,-1,1,2], target = 1
     * 输出:2
     * 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
     * <p>
     * 提示:
     * 3 <= nums.length <= 10^3
     * -10^3 <= nums[i] <= 10^3
     * -10^4 <= target <= 10^4
     * @Author 
     * @Date 2020/6/24
     **/
    public class ThreeSumClosest {
    }
    
    /**
     *  解法1:排序+双指针,时间复杂度为O(n^2)
     */
    public static int threeSumClosest(int[] nums, int target) {
    	// 先排序,时间复杂度O(nlgn)
    	Arrays.sort(nums);
    
    	int len = nums.length;
    	int ans = nums[0] + nums[1] + nums[2];
    	int sum = 0;
    	
    	// 取某一元素,然后设置两指针从该元素之后的元素两端遍历,获取其中的最小和
    	// 双指针时间复杂度为O(n^2)
    	for (int i = 0; i < len - 2; i++) {
    		int L = i + 1, R = len - 1;
    
    		while (L < R) {
    			sum = nums[i] + nums[L] + nums[R];
    			if (sum == target) return target;
    
    			if(Math.abs(target - sum) < Math.abs(target - ans))
    				ans = sum;
    				
    			if (sum > target) R--;
    			if (sum < target) L++;
    		}
    
    	}
    	return ans;
    }
    
    // 测试用例
    public static void main(String[] args) {
        int[] nums = new int[]{-1, 2, 1, -4};
        int target = 1;
        int ans = threeSumClosest(nums, target);
    
        System.out.println("demo01 result:" + ans);
    }
    
  • 相关阅读:
    Oracle RMAN快速入门指南
    防止SQL注入
    脚本获取参数 
    回车下一个
    DataTable
    C# Eval
    C#过滤所有HTML代码的函数
    反射
    gridview格式化问题
    绑定
  • 原文地址:https://www.cnblogs.com/fyusac/p/13186425.html
Copyright © 2011-2022 走看看