Coding Test/LeetCode

[LeetCode] 977. Squares of a Sorted Array c++

owls 2022. 12. 23. 14:10
728x90
  • 문제

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

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].

주어진 배열의 원소들을 제곱한뒤 오름차순으로 재정렬하여 답을 구하는 문제이다.

 

  • 문제 해결

sort함수를 사용한 문제 풀이이다.

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        vector<int> result;
        for(const auto& it: nums){
            result.push_back(it * it);
        }
        sort(result.begin(), result.end());
        return result;
    }
};

 

다른 방법

tow pointer 방식을 사용하는 방법도 있다.

class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        vector<int> res(A.size());
        int l = 0, r = A.size() - 1;
        for (int k = A.size() - 1; k >= 0; k--) {
            if (abs(A[r]) > abs(A[l])) res[k] = A[r] * A[r--];
            else res[k] = A[l] * A[l++];
        }
        return res;
    }
};
728x90