카테고리 없음

[LeetCode] Squares of a Sorted

JUNGKEUNG 2021. 9. 7. 16:45

https://leetcode.com/explore/learn/card/fun-with-arrays/523/conclusion/3574/

 

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

 

Success

 

내림차수가 아닌 순서로 정렬된 정수배열을 각 숫자의 제곱 배열을 내림차수가 아닌순서로 정렬 하는 문제이다

 

풀이

 

s라는 배열에 nums 배열의 길이만큼 받는데 nums 제곱한 값을 s의 인덱스값으로 넣어주고 오름차순으로 정렬해준다. 

class Solution {
    public int[] sortedSquares(int[] nums) {
        int [] s = new int[nums.length];
        for(int i = 0; i < nums.length; i++){
            s[i] = nums[i] * nums[i];
        }
        Arrays.sort(s);
        return s;
    }
}

다른 풀이

투 포인트 방식으로 풀은 문제이다. 

반복문을 뒤에서 부터 돌게하여 왼쪽 끝에 있는 인덱스의 값과 오른쪽 끝에 있는 인덱스 값을 비교하여 큰값을 제곱한 후 새로운 배열에 뒤에서 부터 채워가는 방법이다.

class Solution {
    public int[] sortedSquares(int[] nums) {
        int n = nums.length;
        int[] result = new int[n];
        int left = 0;
        int right = n - 1;

        for (int i = n - 1; i >= 0; i--) {
            int square;
            if (Math.abs(nums[left]) < Math.abs(nums[right])) {
                square = nums[right];
                right--;
            } else {
                square = nums[left];
                left++;
            }
            result[i] = square * square;
        }
        return result;
    }
}