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 wowould 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 ).Original question link: https://oj.leetcode.com/problems/3sum-closest/
Question: given an array S, find the three numbers in S to bring them closer to the target value. And returns its sum.
Public int threeSumClosest (int [] num, int target) {int min = Integer. MAX_VALUE; int result = 0; Arrays. sort (num); for (int I = 0; I <num. length; I ++) {int j = I + 1; int k = num. length-1; while (j <k) {int sum = num [I] + num [j] + num [k]; int minus = Math. abs (sum-target); if (minus = 0) return sum; if (minus <min) {min = minus; result = sum;} if (sum <= target) j ++; elsek --;} return result ;}