我的js算法爬坑之旅-有序数组的平方

746 阅读1分钟

第九天:力扣第977题,有序数组的平方

地址:leetcode-cn.com/problems/sq…

思路:先用绝对值排序,然后进行平方操作。

var sortedSquares = function(A) {
    A.sort(compare);//一定要用函数比较
    function compare(value1, value2) {
        if (Math.abs(value1) > Math.abs(value2) ) {
            return 1;
        } else if (Math.abs(value1)<  Math.abs(value2)) {
            return -1;
        } else {
            return 0;
        }
    }
    var mapResult = A.map(function(item){
        return item * item;
    });//平方操作
    return mapResult;
};
执行用时:128 ms, 在所有 JavaScript 提交中击败了92.46%的用户
内存消耗:44.6 MB, 在所有 JavaScript 提交中击败了12.82%的用户

其他的就是双指针了,没啥看的。

var sortedSquares = function (A) {
  /* 中间开始的双指针 */
  const resArr = [], len = A.length;
  let left = 0, right = len;

  while (left < right) { // 找到中间的数
    const mid = left + ((right - left) >> 1);

    if (A[mid] < 0) {
      left = mid + 1;
    } else if (A[mid] > 0) {
      right = mid;
    } else {
      left = right = mid
      break;
    }
  }
  --left;
  while (left >= 0 || right < len) {
    if (right >= len || (left >= 0 && -A[left] < A[right])) {
      resArr.push(A[left] ** 2);
      --left;
    } else {
      resArr.push(A[right] ** 2);
      ++right;
    }
  }