[JS] Squares of a Sorted Array

2022. 7. 29. 15:30

🔒 문제 (LeetCode 977)

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.

 

Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?

 

🌊 입출력

Example 1:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]

 


 

🔑 해결

🌌 알고리즘 - two pointers

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortedSquares = function(nums) {
    const len = nums.length;
    const result = new Array(len);
    let [l, r, p] = [0, len - 1, len - 1];
    
    while(p >= 0) {
        if(Math.abs(nums[l]) > Math.abs(nums[r])) {
            result[p] = nums[l] * nums[l];
            l++;
        } else {
            result[p] = nums[r] * nums[r];
            r--;
        }
        p--;
    }
    
    return result;
};

'코딩테스트 (JS) > 투포인터' 카테고리의 다른 글

[JS] Reverse Words in a String III  (0) 2022.07.29
[JS] Reverse String  (0) 2022.07.29
[JS] Two Sum II - Input Array Is Sorted  (0) 2022.07.29
[JS] Move Zeroes  (0) 2022.07.29
[JS] Rotate Array  (0) 2022.07.29

+ Recent posts