Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Squares of a Sorted Array #31

Open
cheatsheet1999 opened this issue Sep 11, 2021 · 0 comments
Open

Squares of a Sorted Array #31

cheatsheet1999 opened this issue Sep 11, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

cheatsheet1999 commented Sep 11, 2021

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

Screen Shot 2021-09-10 at 7 24 28 PM

Here is O(n) solution because the intuitive version is trivial

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortedSquares = function(nums) {
    //1. We declare a result array first
    let res = [];
    //2. Put two pointers at the front and end
    let l = 0;
    let r = nums.length - 1;
    //3. Declare a special pointer 'p' for the result array only, we should make p points to the last of the array instead of 1st index, because absolute value of a negative number may become very large 
    let p = r;
    
    while(l <= r) {
        if(nums[l] ** 2 > nums[r] ** 2) {
            res[p] = nums[l] ** 2;
            l++;
            p--;
        } else {
            res[p] = nums[r] ** 2;
            r--;
            p--;
        }
    }
    return res;
    
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant