반응형

https://leetcode.com/problems/squares-of-a-sorted-array

 

Squares of a Sorted Array - LeetCode

Can you solve this real interview question? Squares of a Sorted Array - Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.   Example 1: Input: nums = [-4,-1,0,3,10] Out

leetcode.com

 

투포인터를 이용하면 선형 시간에 풀 수 있었습니다.

좌우측 포인터를 검사하며, 절댓값이 더 큰 값의 제곱 수를 배열에 기억해주고, 포인터를 이동해줍니다.

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        vector<int> res(nums.size());
        int l = 0, r = nums.size() - 1, idx = nums.size();
        while(idx--) {
            if(abs(nums[l]) < abs(nums[r])) {
                res[idx] = nums[r] * nums[r--];
            } else {
                res[idx] = nums[l] * nums[l++];
            }
        }
        return res;
    }
};
반응형

'Algorithm' 카테고리의 다른 글

LeetCode 141. Linked List Cycle  (1) 2024.03.07
LeetCode 19. Remove Nth Node From End of List  (0) 2024.03.03
LeetCode 1609. Even Odd Tree  (0) 2024.02.29
LeetCode 543. Diameter of Binary Tree  (1) 2024.02.29
LeetCode 268. Missing Number  (0) 2024.02.20

+ Recent posts