LeetCode - 3Sum Closest
生活随笔
收集整理的這篇文章主要介紹了
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).
思路:
和3sum一樣,排序之后,先確定第一個元素,然后對余下元素進行兩邊夾。
package sum;import java.util.Arrays;public class ThreeSumClosest {public int threeSumClosest(int[] nums, int target) {int len = nums.length;Arrays.sort(nums);int delta = nums[0] + nums[1] + nums[2] - target;for (int i = 0; i < len - 2;) {int l = i + 1;int r = len - 1;while (l < r) {int tmp = nums[i] + nums[l] + nums[r] - target;if (Math.abs(tmp) < Math.abs(delta))delta = tmp;if (tmp == 0)return target;if (tmp < 0)++l;else--r;}do { ++i; } while (i < len && nums[i] == nums[i - 1]);}return target + delta;}public static void main(String[] args) {// TODO Auto-generated method stubint[] nums = { -1, 2, 1, -4 };int target = 1;ThreeSumClosest t = new ThreeSumClosest();System.out.println(t.threeSumClosest(nums, target));}}?
轉載于:https://www.cnblogs.com/null00/p/5025899.html
總結
以上是生活随笔為你收集整理的LeetCode - 3Sum Closest的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于.NET
- 下一篇: JMeter之JMS接口测试