[LeetCode] 3Sum Closest
2014-04-27 17:15
357 查看
这个还是用到了以前的一个技巧,先排序,然后从两头往中间找最合适的数。不过是多了一层循环,先选定一个数,然后再去试另外两个数。
public class Solution { public int threeSumClosest(int[] num, int target) { List<Integer> sortedNum = new ArrayList<Integer>(); for (int i = 0; i < num.length; ++i) { sortedNum.add(num[i]); } Collections.sort(sortedNum); int closest = num[0] + num[1] + num[2]; int min = Math.abs(closest - target); for (int i = 0; i < num.length - 2; ++i) { int num1 = sortedNum.get(i); for (int j = i + 1, k = (num.length - 1); j < k;) { int temp = num1 + sortedNum.get(j) + sortedNum.get(k); if (temp > target) { --k; } else { ++j; } if (Math.abs(temp - target) < min) { min = Math.abs(temp - target); closest = temp; } } } return closest; } }
相关文章推荐
- leetcode(M) 3sum closest
- LeetCode:3Sum Closest
- 【LeetCode】3Sum Closest
- LeetCode16 3Sum Closest
- leetcode(2)3sum-closest
- leetcode16 3Sum Closest
- [Leetcode]3Sum Closest
- leetcode 16. 3Sum Closest
- [LeetCode]3Sum Closest
- [leetcode] 3Sum Closest
- [LeetCode] 3Sum Closest
- Leetcode 1. Two Sum & 15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- leetcode: 3SumClosest
- LeetCode 16. 3Sum Closest
- C#解leetcode 16. 3Sum Closest
- Leetcode: 3Sum Closest
- LeetCode 16. 3Sum Closest
- LeetCode:3Sum Closest
- LeetCode --- 16. 3Sum Closest
- LeetCode-3Sum Closest