Leetcode 16 3Sum Closest
2015-07-26 00:09
393 查看
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 would 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).
Solution1
和3 Sum问题一样,都是固定第一个数然后再去扫描剩余的两个数。这里比3 Sum好处理的地方只需要计算绝对值而不需要去考虑重复的情况。代码如下:import java.util.Arrays; public class Solution { public int threeSumClosest(int[] nums, int target) { long result = Integer.MAX_VALUE;//需要将result定义成long类型,因为有可能下面在相减的时候超出范围 Arrays.sort(nums); for(int i=0;i<nums.length;i++){ for(int k=i+1,j=nums.length-1;k<j;){ int temp = nums[i] + nums[j] + nums[k]; if(Math.abs(temp-target)<Math.abs(result-target)) result = temp; if(temp<target) k++; else j--; } } return (int)result; } }
Solution2
解法一在定义result的时候将其定义成为了一个long类型的数据,如果觉得这种定义很不优雅的话,也可以用如下的方式:import java.util.Arrays; public class Solution { public int threeSumClosest(int[] nums, int target) { int n = nums.length; Arrays.sort(nums); int result = nums[0]+nums[1]+nums[n-1];//先将result赋值为第一个能找到的 for(int i=0;i<n-2;i++){ for(int k=i+1,j=n-1;k<j;){ int temp = nums[i] + nums[j] + nums[k]; if(Math.abs(temp-target)<Math.abs(result-target)) result = temp; if(temp<target) k++; else j--; } } return result; } }
相关文章推荐
- 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
- 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 题解
- LeetCode [Day 6] ZigZag Conversion 题解