notes/OJ notes/pages/Leetcode Squares-of-a-Sorted-Array.md
2022-09-03 15:17:25 +08:00

1.9 KiB

Leetcode Squares-of-a-Sorted-Array

2022-07-10 08:50

Algorithms:

#algorithm #two_pointers

Data structures:

#DS #array

Difficulty:

#coding_problem #difficulty-easy

Additional tags:

#leetcode

Revisions:

N/A


Problem

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number 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?

Examples

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]

Constraints

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

Thoughts

[!summary] This is a #two_pointers

Using two pointers. One from left, one from right end. fill the array in backwards order.

Solution

cpp

class Solution {
public:
  vector<int> sortedSquares(vector<int> &nums) {
    // Double pointers, since array is sorted and access in order.
    // O(2n)

    int mid;
    int size = nums.size();
    int left = 0, right = size - 1;
    int count = size - 1;
    vector<int> answer(size);

    for (int i = 0; i < size; i++) {
      nums[i] = nums[i] * nums[i];
    }

    while (left <= right) {
      if (nums[left] >= nums[right]) {
        answer[count--] = nums[left];
        left++;
      } else if (nums[right] > nums[left]) {
        answer[count--] = nums[right];
        right--;
      }
    }

    return answer;
  }
};