LeetCode 016 3Sum Closest
2016-05-05 12:11
417 查看
题目大意是在数组中找3个数,使其的和最靠近给出的目标整数target。
思路和上一题3Sum一样,但是不能用hashmap因为要找的是最接近的数。
最快的算法是先排序。从小到大枚举最小的第一个数。然后从两边往中间扫描,得出第二个和第三个数。
需要注意的是,虽然时间复杂度都一样,但是一些常数上的优化可以大大加速程序:
跳过重复的数
当最小数*3超过target时直接返回。
当中间数*2超过(target-最小数)时跳过此轮循环
当三个数相加等于target时直接返回
加了以上优化,程序从52ms加快到8ms。
思路和上一题3Sum一样,但是不能用hashmap因为要找的是最接近的数。
最快的算法是先排序。从小到大枚举最小的第一个数。然后从两边往中间扫描,得出第二个和第三个数。
需要注意的是,虽然时间复杂度都一样,但是一些常数上的优化可以大大加速程序:
跳过重复的数
当最小数*3超过target时直接返回。
当中间数*2超过(target-最小数)时跳过此轮循环
当三个数相加等于target时直接返回
加了以上优化,程序从52ms加快到8ms。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [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 题解