Leetcode || 3Sum Closest
2015-10-30 12:03
423 查看
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.
在3Sum基础上改改就行
在3Sum基础上改改就行
package pack; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; /* * 求三数和为0,遍历一个数,以它为定点,再转化为2Sum */ class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); HashSet hs = new HashSet(); //最后不会有重复 int result = 0; int sum = 0; int closestDis = Integer.MAX_VALUE; for(int i=0; i<nums.length; i++) { int left = i + 1; //最关键的地方,如果是想办法去掉定点后left=0,会重复计算 int right = nums.length-1; while(left < right) { sum = nums[left] + nums[right] + nums[i]; if(sum > target) { if(sum-target < closestDis) { closestDis = sum - target; result = sum; } right--; } else if(sum < target) { if(target-sum < closestDis) { closestDis = target - sum ; result = sum; } left++; } else { return sum; } } } return result; } } public class Main { public static void main(String[] args) { int[] arr = new int[] {1, 1, 1, 0}; System.out.println(new Solution().threeSumClosest(arr, -10)); } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解