๋ฐ์ํ
ํ๋ก๊ทธ๋๋จธ์ค LV.0 ๋ชจ์
์ต๋น๊ฐ ๊ตฌํ๊ธฐ
๋ฌธ์ ์ค๋ช
์ต๋น๊ฐ์ ์ฃผ์ด์ง ๊ฐ ์ค์์ ๊ฐ์ฅ ์์ฃผ ๋์ค๋ ๊ฐ์ ์๋ฏธํฉ๋๋ค. ์ ์ ๋ฐฐ์ด array๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, ์ต๋น๊ฐ์ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด๋ณด์ธ์. ์ต๋น๊ฐ์ด ์ฌ๋ฌ ๊ฐ๋ฉด -1์ return ํฉ๋๋ค.
์ ํ ์ฌํญ
- 0 < array์ ๊ธธ์ด < 100
- 0 ≤ array์ ์์ < 1000
์ ์ถ๋ ฅ ์
array | result |
[1, 2, 3, 3, 3, 4] | 3 |
[1, 1, 2, 2] | -1 |
[1] | 1 |
์ ์ถ๋ ฅ ์ ์ค๋ช
์ ์ถ๋ ฅ ์ #1
- [1, 2, 3, 3, 3, 4]์์ 1์ 1๊ฐ 2๋ 1๊ฐ 3์ 3๊ฐ 4๋ 1๊ฐ๋ก ์ต๋น๊ฐ์ 3์ ๋๋ค.
์ ์ถ๋ ฅ ์ #2
- [1, 1, 2, 2]์์ 1์ 2๊ฐ 2๋ 2๊ฐ๋ก ์ต๋น๊ฐ์ด 1, 2์ ๋๋ค. ์ต๋น๊ฐ์ด ์ฌ๋ฌ ๊ฐ์ด๋ฏ๋ก -1์ return ํฉ๋๋ค.
์ ์ถ๋ ฅ ์ #3
- [1]์๋ 1๋ง ์์ผ๋ฏ๋ก ์ต๋น๊ฐ์ 1์ ๋๋ค.
์ ์ถ
import Foundation
func solution(_ array:[Int]) -> Int {
var dict = [Int: Int]()
for a in array{
dict[a, default: 0] += 1
}
let max = dict.max{$0.value <= $1.value}!
return dict.values.filter{$0 == max.value}.count > 1 ? -1 : max.key
}
๋์ ๋๋ฆฌ๋ฅผ ์ ์ธํ์ฌ ๋ฐฐ์ด์ ์์๋ฅผ key ๊ฐ์ผ๋ก, ๊ฐ ์์์ ๊ฐ์๋ฅผ value ๊ฐ์ผ๋ก ์ ์ฅํ๋ค.
๋์ ๋๋ฆฌ์์ value๊ฐ ๊ฐ์ฅ ํฐ ๊ฐ์ ์ฐพ์ ๊ฐ์ฅ ํฐ value๋ฅผ ๊ฐ์ง key๊ฐ ์ฌ๋ฌ ๊ฐ๋ผ๋ฉด -1์, ์๋๋ผ๋ฉด key๋ฅผ ๋ฐํํ๋ค.
๋ค๋ฅธ ํ์ด
func solution(_ array: [Int]) -> Int {
let sorted = Dictionary(grouping: array) { $0 }.sorted { $0.value.count > $1.value.count }
return sorted.count > 1 && sorted[0].value.count == sorted[1].value.count ? -1 : sorted[0].key
}
๋ฐฐ์ด์ ๋์ ๋๋ฆฌ๋ก ๊ทธ๋ฃนํํ ํ value์ ๊ฐ์์ ๋ฐ๋ผ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌํ๋ค.
์ ๋ ฌํ ๋ฐฐ์ด์์ ์ฒซ ๋ฒ์งธ ๋ฐฐ์ด์ ๊ฐ์์ ๋ ๋ฒ์งธ ๋ฐฐ์ด์ ๊ฐ์๊ฐ ๊ฐ๋ค๋ฉด -1์, ์๋๋ผ๋ฉด ์ฒซ ๋ฒ์งธ ๋ฐฐ์ด์ ํค๊ฐ์ ๋ฐํํ๋ค.
๋ฐ์ํ
'โจ๏ธ Language > swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ํ๋ก๊ทธ๋๋จธ์ค LV.0 ํผ์ ๋๋ ๋จน๊ธฐ (1) (0) | 2022.11.30 |
---|---|
[Swift] ํ๋ก๊ทธ๋๋จธ์ค LV.0 ์ง์๋ ์ซ์ด์ (0) | 2022.11.30 |
[Swift] ํ๋ก๊ทธ๋๋จธ์ค LV.0 ์ค์๊ฐ ๊ตฌํ๊ธฐ (0) | 2022.11.30 |
[Swift] ํ๋ก๊ทธ๋๋จธ์ค LV.0 ๋ฐฐ์ด ๋๋ฐฐ ๋ง๋ค๊ธฐ (0) | 2022.11.29 |
[Swift] ํ๋ก๊ทธ๋๋จธ์ค LV.0 ๋ถ์์ ๋ง์ (0) | 2022.11.29 |