Skip to content

Latest commit

 

History

History
57 lines (49 loc) · 1.57 KB

16. 3Sum Closest.md

File metadata and controls

57 lines (49 loc) · 1.57 KB

leetcode-cn Daily Challenge on June 24, 2020.


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).

Solution

  • mine
    • Java

      Runtime: 3 ms, faster than 98.26%, Memory Usage: 39.1 MB, less than 6.67% of Java online submissions

      same as 3Sum.

      public int threeSumClosest(int[] nums, int target) {
          Arrays.sort(nums);
          int dx = Integer.MAX_VALUE;
          int res = 0;
          for(int i = 0; i < nums.length - 2; i++){
              if(i != 0 && nums[i] == nums[i - 1]){
                  continue;
              }
              int s = i + 1, e = nums.length - 1;
              while(s < e){
                  int sum = nums[i] + nums[s] + nums[e];
                  if(sum == target){
                      return sum;
                  }
                  int t = Math.abs(sum - target);
                  if(t < dx){
                      dx = t;
                      res = sum;
                  }
                  if(sum < target){
                      s++;
                  }else{
                      e--;
                  }
              }
          }
          return res;
      }