알고리즘

[LeetCode] Squares of a Sorted Array

JUNGKEUNG 2021. 9. 15. 08:41

https://leetcode.com/explore/learn/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

문제

정수 배열에 있는값들을 제곱근하고 정렬 후 출력하세요

 

풀이

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

nums배열 을 s에 담아주고 nums배열을 제곱근 해서 s배열에 담아준다.

Arrays.sort을 사용해서 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;
    }
}

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