알고리즘/해결

LeetCode 905. Sort Array By Parity

언클린 2020. 1. 19. 19:26
728x90

1. 문제(원본)

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

 

Example 1:

Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

 

Note:

  1. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

2. 문제

임의의 Int형 배열을 받아 짝수를 먼저 출력한 후 홀수를 출력한다.

 

3. 나의 답

class Solution {

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

        var newArray: [Int] = []

        for element in A {

            switch element % 2  {

            case 0: // 짝수

                newArray.insert(element, at: 0)

            default: // 홀수

               newArray.append(element)

            }

        }

        return newArray

    }

}

4. 다른 유저의 답

 

#1

class Solution {

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

        return

            A.filter({ $0 % 2 == 0 }) +

            A.filter({ $0 % 2 == 1 })

    }

}

 

#2

class Solution {

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

        var evens = [Int]()

        var odds = [Int]()

        

        for num in A {

            num % 2 == 0 ? evens.append(num) : odds.append(num)

        }

        

        return evens + odds

    }

}

5. 마무리

이번 문제는 쉽게 풀었다고 생각했는데 다른 유저들의 답변을 보고 더 빠르게 풀 수 있다는 것을 알았다.

배열도 +로 합쳐진다는 새로운 지식도 습득할 수 있었다.

728x90