πŸ“– Problem Solution/Programmers

[Swift] ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ μ›”κ°„ μ½”λ“œ μ±Œλ¦°μ§€1 μŠ€νƒ€ μˆ˜μ—΄

Fomagran πŸ’» 2021. 11. 6. 23:23
728x90
λ°˜μ‘ν˜•

Problem

 

 

μ½”λ”©ν…ŒμŠ€νŠΈ μ—°μŠ΅ - μŠ€νƒ€ μˆ˜μ—΄

 

programmers.co.kr


Solution

 

1. a에 μžˆλŠ” μˆ«μžλ“€μ˜ 갯수λ₯Ό μ„Έμ€€λ‹€.

 

μˆ«μžλ“€μ˜ 갯수λ₯Ό μ„Έμ£ΌλŠ” μ΄μœ λŠ” κ°―μˆ˜κ°€ λ§Žμ€ 숫자둜 μ •λ ¬ν•˜μ—¬ μ‹œκ°„ 초과λ₯Ό 막기 μœ„ν•΄μ„œ μž…λ‹ˆλ‹€.

 

func countNumbers(a:[Int]) -> [Int:Int] {
    var countDic:[Int:Int] = [:]
    for n in a {
        if countDic[n] == nil {
            countDic[n] = 1
        }else {
            countDic[n]! += 1
        }
    }
    return countDic
}

 

2. 각 μˆ«μžλ“€μ˜ κ°€μž₯ κΈ΄ λΆ€λΆ„ μˆ˜μ—΄ 길이λ₯Ό ꡬ해쀀닀.

 

κ°„λ‹¨ν•˜κ²Œ μ„€λͺ…ν•˜λ©΄ 각 μˆ«μžλ“€μ˜ μ•ž λ’€λ₯Ό λΉ„κ΅ν•΄μ€λ‹ˆλ‹€.

 

λ§Œμ•½ μ•žκ³Ό λ’€ 쀑 ν•˜λ‚˜λΌλ„ ν˜„μž¬ μˆ«μžμ™€ 같지 μ•Šμ€ μˆ«μžκ°€ μžˆλ‹€λ©΄ +2 ν•΄μ€λ‹ˆλ‹€.

 

κ·Έ λ‹€μŒ ν•΄λ‹Ή 숫자λ₯Ό ν˜„μž¬ 숫자둜 λ°”κΏ”μ€λ‹ˆλ‹€.

 

func findLongSubsequence(n:Int,a:[Int]) -> Int {
    var numbers = a
    var length:Int = 0
    if a[0] == n && a[1] != n {
        length += 2
        numbers[1] = n
    }
    for i in 1..<numbers.count-1 {
        if a[i] == n {
            if numbers[i-1] != n {
                numbers[i-1] = n
                length += 2
            }else if numbers[i+1] != n  {
                numbers[i+1] = n
                length += 2
            }
        }
    }
    if numbers[a.count-1] == n && numbers[a.count-2] != n {
        length += 2
    }
    return length
}

 

3. 각 μˆ«μžλ“€μ˜ κ°€μž₯ κΈ΄ λΆ€λΆ„ μˆ˜μ—΄ 길이 쀑 κ°€μž₯ κΈ΄ 것을 λ°˜ν™˜ν•œλ‹€.

 

μ‹œκ°„ 초과λ₯Ό 막기 μœ„ν•΄ 숫자의 κ°―μˆ˜κ°€ 더 λ§Žμ€ κ²ƒμœΌλ‘œ μ •λ ¬ν•œ λ‹€μŒ μˆœν™˜μ„ μ§„ν–‰ν•©λ‹ˆλ‹€.

 

λ§Œμ•½ answer보닀 숫자의 갯수 * 2κ°€ 더 μž‘λ‹€λ©΄ answer보닀 더 클 μˆ˜κ°€ μ—†μœΌλ―€λ‘œ  λ‹€μŒμœΌλ‘œ λ„˜μ–΄κ°€μ€λ‹ˆλ‹€.

 

func findMaxLength(a:[Int]) -> Int {
    var answer:Int = 0
    let sortCounts = countNumbers(a: a).sorted{$0.value > $1.value}
    for dic in sortCounts {
        if dic.value * 2 < answer { continue }
        let length = findLongSubsequence(n:dic.key, a:a)
        answer = max(answer,length)
    }
    return answer
}

Source Code

 


P.S

 

μ²˜μŒμ—” κ°€μž₯ 숫자의 κ°―μˆ˜κ°€ λ§Žμ€ κ²ƒμ˜ κ°€μž₯ κΈ΄ λΆ€λΆ„ μˆ˜μ—΄μ„ μ°Ύμ•„μ„œ λ°˜ν™˜ν–ˆλ‹€.

 

근데 계속 ν…ŒμŠ€νŠΈ μΌ€μ΄μŠ€ 28번이 ν‹€λ Έλ‹€...

 

κ·Έλž˜μ„œ μ§ˆλ¬Έν•˜κΈ°λ₯Ό 톡해 λ΄€λ”λ‹ˆ λ§Œμ•½ μ΄λ ‡κ²Œ aκ°€ μ£Όμ–΄μ‘Œμ„κ²½μš° -> [4, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 3]

 

1이 κ°€μž₯ λ§Žμ§€λ§Œ κ°€μž₯ κΈ΄ λΆ€λΆ„ μˆ˜μ—΄μ€ 0을 μ΄μš©ν•΄μ„œ λ§Œλ“€μ–΄μ•Ό ν•œλ‹€...

 

κ·Έλž˜μ„œ κ²°κ΅­ λͺ¨λ“  숫자λ₯Ό 확인해봐야 ν–ˆμ—ˆλ‹€..

728x90
λ°˜μ‘ν˜•