返回

精彩不断,勇攀排序与双指针高峰:突破`16. 最接近的三数之和`难关

前端

随着我们踏入算法的世界,16. 最接近的三数之和挑战等待着我们。在本文中,我们将携手揭开算法背后的面纱,通过一步步的分析和实现,最终解决难题。首先,让我们来理解问题本身。

题目要求我们从给定数组中找出三个整数,使得它们的和与目标值最接近。这里,我们采用排序加双指针的方法来解决问题。首先,我们将数组进行排序,以确保元素从小到大排列。排序之后,我们使用两个指针,分别指向数组的开头和结尾。

然后,我们将中间元素与目标值进行比较。如果中间元素大于目标值,那么我们将右指针向左移动。如果中间元素小于目标值,那么我们将左指针向右移动。这个过程会一直进行,直到中间元素等于目标值,或者左右指针相遇。

在移动指针的过程中,我们将不断更新当前三个元素的和,并记录与目标值最接近的和。当左右指针相遇时,我们返回当前三个元素的和,作为与目标值最接近的和。

现在,让我们用代码来实现这个算法。首先,我们导入必要的库:

import java.util.Arrays;

然后,我们定义我们的函数来解决问题:

public static int threeSumClosest(int[] nums, int target) {
  // Sort the array
  Arrays.sort(nums);

  // Initialize the closest sum to a large value
  int closestSum = Integer.MAX_VALUE;

  // Iterate over the array
  for (int i = 0; i < nums.length - 2; i++) {
    // Skip duplicate elements
    if (i > 0 && nums[i] == nums[i - 1]) {
      continue;
    }

    // Initialize the left and right pointers
    int left = i + 1;
    int right = nums.length - 1;

    // While the left pointer is less than or equal to the right pointer
    while (left < right) {
      // Calculate the current sum
      int currentSum = nums[i] + nums[left] + nums[right];

      // Update the closest sum if necessary
      if (Math.abs(currentSum - target) < Math.abs(closestSum - target)) {
        closestSum = currentSum;
      }

      // Move the left or right pointer depending on the comparison
      if (currentSum < target) {
        left++;
      } else {
        right--;
      }
    }
  }

  // Return the closest sum
  return closestSum;
}

最后,让我们测试我们的函数:

public static void main(String[] args) {
  int[] nums = {-1, 2, 1, -4};
  int target = 1;

  int closestSum = threeSumClosest(nums, target);

  System.out.println("The closest sum is: " + closestSum);
}

运行这段代码,我们会得到输出:

The closest sum is: 2

这表明数组[-1, 2, 1, -4]中,三个元素12-1的和最接近目标值1

通过本文,我们深入剖析了16. 最接近的三数之和编程挑战,从算法原理到代码实现,一步步揭开难题的面纱。希望这篇文章能够帮助您更深入地理解算法,并提升您的编程能力。如果您有任何问题,请随时留言。