1. 문제(원본)
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
Example 1:
Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2] Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] Output: true
Constraints:
- 1 <= arr.length <= 1000
- -1000 <= arr[i] <= 1000
2. 문제
임의의 Int형 배열을 받아 index의 중복 수가 모두 일치하지 않으면 true를 반환, 중복 수가 같다면 false를 반환한다.
3. 나의 답
class Solution {
func uniqueOccurrences(_ arr: [Int]) -> Bool {
// inner func
// 기존의 함수의 기준치를 체크하기 위하여 중복을 제거
func makeSet() -> [Int] {
var resultArray: [Int] = []
var setArray: Set = []
for element in arr {
// 중복을 허용하지 않는 Set
setArray.insert(element)
}
for element in setArray {
resultArray.append(element)
}
return resultArray
}
// 해당 기준치들의 갯수를 확인
func makeFilter(_ setArray: [Int], _ arr: [Int]) -> [Int] {
var lastCheckArray: [Int] = []
for element in setArray {
let count = arr.filter { $0 == element }.count
lastCheckArray.append(count)
}
return lastCheckArray
}
// 같은 수가 존재한다면 return false 없다면 return true
func resultMake(_ lastCheckArray: [Int]) -> Bool {
for element in lastCheckArray {
let check = lastCheckArray.filter { $0 == element }.count
if check > 1 {
return false
}
}
return true
}
// inner func end
return resultMake(makeFilter(makeSet(), arr))
}
}
4. 다른 유저의 답
#1
class Solution {
func uniqueOccurrences(_ arr: [Int]) -> Bool {
var numDict: [Int: Int] = [:]
for num in arr {
if let val = numDict[num] {
numDict[num] = val + 1
} else {
numDict[num] = 1
}
}
let values = Array(numDict.values)
return values.count == Set(values).count
}
}
#2
class Solution {
func uniqueOccurrences(_ arr: [Int]) -> Bool {
let countMap = arr.reduce(into: [Int:Int](), { (acc, curr) in
acc[curr, default: 0] += 1
})
return Set(Array(countMap.values)).count == countMap.keys.count
}
}
5. 마무리
다른 유저들의 답을 보면은 간단히 할 수 있는 것을 나는 너무 어렵게 푼 것 같다. 좀 더 swift의 Set과 여러가지 배열의 함수들을 활용할 수 있도록 해야겠다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode977. Squares of a Sorted Array (0) | 2020.01.26 |
---|---|
LeetCode709. To Lower Case (0) | 2020.01.26 |
LeetCode 905. Sort Array By Parity (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 |