使用针对Leetcode 973的快速选择算法的bug

时间:2019-04-07 06:38:54

标签: javascript algorithm

我正在使用快速选择算法来解决此问题,以下算法遇到了Max call stack exceeded错误,但无法找出错误的位置...感谢您的帮助: https://leetcode.com/problems/k-closest-points-to-origin/description/

`我们在飞机上有一个点列表。找到最接近原点(0,0)的K个点。

(这里,平面上两点之间的距离就是欧氏距离。)

您可以按任何顺序返回答案。答案肯定是唯一的(除了它的顺序。)

/**
 * @param {number[][]} points
 * @param {number} K
 * @return {number[][]}
 */
var kClosest = function(points, K) {
    quickSelect(points, K, 0, points.length - 1)
    return points.slice(0, K)
};

function quickSelect(points, K, low, high) {
  if (low >= high) return;
  const partitionIndex = partition(points, low, high);
  if (partitionIndex === K - 1) 
    return;
  if (partitionIndex < K - 1) {
    quickSelect(points, K, partitionIndex + 1, high);
  } else {
    quickSelect(points, K, low, partitionIndex - 1);
  }
}

function partition(points, low, high) {
  const pivot = points[(low+high)>>2]
  //console.log('pivot:', pivot, (low+high)>>2);

  while(low <= high){
    while(getDist(points[low]) < getDist(pivot)){
      low++;
    }
    while(getDist(points[high]) >getDist(pivot)){
      high--;
    }

    if(low <= high){
      swap(points, low, high);
      low++;
      high--;
    }
  }

  return low;
}

function getDist(point) {
  return point[0] * point[0] + point[1] * point[1];
}

function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]];
}

0 个答案:

没有答案