LeetCode 3Sum Closest 三数求和最接近目标

雨点打透心脏的1/2处 2021-06-24 16:10 461阅读 0赞

试题:
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一样解法

  1. class Solution {
  2. public int threeSumClosest(int[] nums, int target) {
  3. Arrays.sort(nums);
  4. int closest = 0x3f3f3f3f;
  5. int out=0;
  6. for(int i=0; i<nums.length; i++){
  7. int curtarget = target-nums[i];
  8. int f=i+1,t=nums.length-1;
  9. while(f<t){
  10. // System.out.println(" "+nums[i]+" "+nums[f]+" "+nums[t]);
  11. int sum = nums[f] + nums[t];
  12. int close = Math.abs(curtarget-sum);
  13. if(closest>close){
  14. closest = close;
  15. out = nums[i] + nums[f] +nums[t];
  16. }
  17. if(curtarget<=sum){
  18. t--;
  19. }else if(curtarget>sum){
  20. f++;
  21. }
  22. }
  23. }
  24. return out;
  25. }
  26. }

发表评论

表情:
评论列表 (有 0 条评论,461人围观)

还没有评论,来说两句吧...

相关阅读