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 <= A.length <= 5000
- 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. 마무리
이번 문제는 쉽게 풀었다고 생각했는데 다른 유저들의 답변을 보고 더 빠르게 풀 수 있다는 것을 알았다.
배열도 +로 합쳐진다는 새로운 지식도 습득할 수 있었다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode977. Squares of a Sorted Array (0) | 2020.01.26 |
---|---|
LeetCode709. To Lower Case (0) | 2020.01.26 |
LeetCode 1207. Unique Number of Occurrences (0) | 2020.01.19 |
LeetCode 1281. Subtract the Product and Sum of Digits of an Integer (0) | 2020.01.13 |
LeetCode 1108. Defanging an IP Address (0) | 2020.01.12 |