알고리즘/해결

LeetCode977. Squares of a Sorted Array

언클린 2020. 1. 26. 17:41
728x90

1. 문제(원본)

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

 

Example 1:

Input: [-4,-1,0,3,10] Output: [0,1,9,16,100]

Example 2:

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

 

Note:

  1. 1 <= A.length <= 10000
  2. -10000 <= A[i] <= 10000
  3. A is sorted in non-decreasing order.

 

2. 문제

각 배열 인덱스의 제곱의 수를 정렬

 

3. 나의 답

class Solution {

    func sortedSquares(_ A: [Int]) -> [Int] {

        return A.map { $0 * $0 }.sorted { $0 < $1 }

    }

}

4. 다른 유저의 답

#1

class Solution {

    func sortedSquares(_ A: [Int]) -> [Int] {

        return A.map { $0 * $0 }.sorted()

    }

}

5. 마무리

sorted()는 자연스럽게 내림차순이라는 것을 배우게 되었다. 

이번 문제는 배열의 함수를 적절히 활용하면 간단하게 풀 수 있는 문제였다.

728x90