leetcode解题之 16. 3Sum Closest Java版
2019-01-03 19:35
447 查看
16. 3Sum Closest
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解题思路:
此问题类似于3SUM,基本算法一样,代码很简单,很容易理解,都有相应的注释
class Solution { public int threeSumClosest(int[] nums, int target) { if(nums==null&&nums.length<3) return 0; Arrays.sort(nums); //对数组进行排序 int min=nums[0]+nums[1]+nums[2]; //i要全部循环,三个数字相加,所以只需要循环到倒数第三个数字即可,即nums.length-2 for(int i=0;i<nums.length-2;i++){ int left=i+1; int right=nums.length-1; // int tmp = target-nums[i]; while(left<right){ if( Math.abs( target-nums[i]-nums[left]-nums[right])<Math.abs(target-min)) //每次查看是不是最小的情况 min= nums[i]+nums[left]+nums[right] ; //如果target减三个数的和小于 target减min,三数之和赋给min //if(nums[left]+nums[right]== target-nums[i]) if(min== target) return target; //如果给定的数字target=三个数之和,直接返回就好了 else if(nums[left]+nums[right]+nums[i]< target) // else if(min< target) //替换之后会出现bug for循环跳到下一圈的时候有可能出现三数之和>target同时绝对值也>min的情况,这时min不会被更新,仍然符合<target的条件,但是实际上三数之和是>target的 left++; //三个数字之和小于给定数字target的话 ,需要将左边的指针右移 else right--; } } return min; } }
相关文章推荐
- leetcode解题之 16. 3Sum Closest Java版(结果离目标值最近三个数字和)
- Java [leetcode 16] 3Sum Closest
- 【小熊刷题】3Sum Closest <Leetcode 16, Java>
- 【leetcode-16】3Sum Closest(java)
- LeetCode解题报告—— Container With Most Water & 3Sum Closest & Letter Combinations of a Phone Number
- LeetCode 16 3sum closest
- LeetCode 16: 3Sum Closest
- LeetCode16 3Sum Closest
- LeetCode 16 3Sum Closest
- Leetcode 16[medium]--3Sum Closest
- LeetCode 16 3Sum Closest
- [Leetcode] 16. 3Sum Closest
- 【leetcode】【16】3Sum Closest
- LeetCode题解-16-3Sum Closest
- [LeetCode] 16. 3Sum Closest
- [LeetCode][Java] 3Sum Closest
- Leetcode 16 - 3Sum Closest
- LeetCode之16_3Sum Closest
- leetcode 16 3Sum Closest
- LeetCode(16)题解--3Sum Closest