본문 바로가기
  • Jetpack 알아보기
LeetCode/Easy

[Java] LeetCode 977 : Squares of a Sorted Array

by 새우버거♬ 2021. 3. 30.

LeetCode # 977


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

 

Example 2:

 

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

 

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.

Solution #1

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

 

Result #1

 

💡 간단하게 Arrays.sort()를 구현하여 문제를 풀었다. 하지만 Arrays.sort()의 시간 복잡도는 O(n log n).


Solution #2 (1ms)

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] result = new int[nums.length];
        int left = 0, 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;
    }
}

 

Result #2

 

💡 left, right 인덱스를 증감시켜 절댓값 비교를 하는 방법으로 풀었다. 1ms로 시간이 감소한 결과를 볼 수 있다.

 

 

 


 

More Algorithm!

 

👇👇

 

github.com/ggujangi/ggu.leet-code

 

ggujangi/ggu.leet-code

LeetCode, Java. Contribute to ggujangi/ggu.leet-code development by creating an account on GitHub.

github.com

 

 

 

 

출처 : leetCode