[LeetCode] Squares of a Sorted Array

아르당·1일 전

LeetCode

목록 보기
211/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

오름차순으로 정렬되어 있는 정수 배열 nums가 주어졌을 때, 각 숫자의 제곱값을 오름차순으로 정렬한 배열을 반환해라.

Example

#1
Input: nums = [-4, -1, 0, 3, 10]
Output: [0, 1, 9, 16, 100]
Explanation: 제곱 후, 배열은 [16, 1, 0, 9, 100]이다.
정렬 후, [0, 1, 9, 16, 100]이다.

#2
Input: nums = [-7, -3, 2, 3, 11]
Output: [4, 9, 9, 49, 121]

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums는 오름차순으로 정렬되어 있다.

Solved

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

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

        return result;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글