LeetCode_16 3SumCloest
Posted BUG
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode_16 3SumCloest相关的知识,希望对你有一定的参考价值。
3Sum Closest
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
1 public int threeSumClosest(int[] nums, int target) { 2 Arrays.sort(nums); 3 int sum = nums[0] + nums[1] + nums[2]; 4 int diff = Math.abs(sum - target); 5 for (int i = 0; i < nums.length - 2; i++) { 6 if (i != 0 && nums[i] == nums[i - 1]) 7 continue; 8 int j = i + 1; 9 int k = nums.length - 1; 10 while (k > j) { 11 int aa = nums[i] + nums[j] + nums[k]; 12 int newDiff = Math.abs(aa - target); 13 if (newDiff < diff) { 14 diff = newDiff; 15 sum = aa; 16 } 17 if (aa < target) { 18 j++; 19 } else { 20 k--; 21 } 22 } 23 } 24 return sum; 25 }
以上是关于LeetCode_16 3SumCloest的主要内容,如果未能解决你的问题,请参考以下文章
Linear regression with one variable算法实例讲解(绘制图像,cost_Function ,Gradient Desent, 拟合曲线, 轮廓图绘制)_矩阵操作(代码片