본문 바로가기

Problem Solving/리트코드

[LeetCode] Squares of a Sorted Array

vector sort하는 법.

sort(벡터이름.begin(), 벡터이름.end());

 

나는 단순히 제곱 해준 후 sort 쓰는 법 생각했는데 most votes에서는 sort안쓰고, 제곱 후 left most, right most 사용해서 비교하면서 새 vector 만들어서 값 넣어줬다. 

 

sort쓸 때의 속도가 input이 많을 때 직접 비교하는 알고리즘 보다 더 빠를지 느릴지 모르겠다.

내가 짠 코드

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int i;
        for(i=0;i<nums.size();i++){
            nums[i] = nums[i]*nums[i];
        }
        sort(nums.begin(),nums.end());
        return nums;
    }
};

Discuss 코드 1

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;
    }
};

 

leetcode.com/explore/featured/card/fun-with-arrays/521/introduction/3240/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

 

'Problem Solving > 리트코드' 카테고리의 다른 글

[LeetCode] Arithmetic SlicesSolution  (0) 2021.02.19
[LeetCode] Linked List Cycle  (0) 2021.02.08
[LeetCode] Number of 1 Bits  (0) 2021.02.08
[LeetCode] 541. Reverse String II  (0) 2021.01.27
[LeetCode] 344. Reverse String  (0) 2021.01.27