本文主要是介绍16 3Sum Closest,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
类似的题目有
1 TwoSum
15 3Sum
18 4Sum
public static int threeSumClosest(int[] nums, int target) {Arrays.sort(nums);int minMinus = 10000;int result = 0;int sum = 0;for (int i = 0; i < nums.length; i++) {int j = i + 1;int k = nums.length - 1;while (j < k) {sum = nums[i] + nums[j] + nums[k];if (sum == target)return 0;int minus = Math.abs(target - sum);if (minus < minMinus) {minMinus = minus;result = sum;}if (sum > target)k--;elsej++;}}return result;}
这篇关于16 3Sum Closest的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!