Skip to content

[Algorithm] GenomicRangeQueryย #140

@hwangJi-dev

Description

@hwangJi-dev

๐Ÿ’ฌย ๋ฌธ์ œ

https://app.codility.com/programmers/lessons/5-prefix_sums/genomic_range_query/


๐Ÿ’ฌย Idea

  • ์ฒ˜์Œ์—” ๊ต‰์žฅํžˆ ๊ฐ„๋‹จํ•œ ๋ฌธ์ œ๋ผ ์ƒ๊ฐํ–ˆ์ง€๋งŒ, ํšจ์œจ์„ฑ ํ…Œ์ŠคํŠธ๋ฅผ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•ด ๊ต‰์žฅํžˆ ์• ๋ฅผ ์ผ๋‹ค.
  • O(N^2)์˜ ํšจ์œจ์„ฑ์„ O(N + M)์œผ๋กœ ๋†’์ด๊ธฐ ์œ„ํ•ด ๊ตฌ๊ฐ„ํ•ฉ์„ ์‚ฌ์šฉํ•ด์ฃผ์—ˆ๋‹ค.
  • a, c, g, t ๊ฐ๊ฐ์˜ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด (t๋Š” ์—†์–ด๋„ ๋จ) ์•ŒํŒŒ๋ฒณ์ด ๋‚˜์˜จ ๊ตฌ๊ฐ„์—๋Š” ์ด์ „ ๊ฐ’ + 1์„ ํ•ด์ฃผ์–ด ์ €์žฅํ•ด์ค€๋‹ค.
  • ์ดํ›„ P๋ฅผ ๋Œ๋ฉด์„œ (P) ์—์„œ (Q + 1) ๊นŒ์ง€์˜ ์ฐจ๊ฐ€ 0 ์ด์ƒ์ผ ๋•Œ a,c,g,t ์ค‘ ์กฐ๊ฑด์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’์„ ans์— appendํ•œ๋‹ค.
    • Q + 1 ๊นŒ์ง€์ธ์ด์œ : ์ด์ „ ์ธ๋ฑ์Šค์™€ ๋น„๊ตํ•˜์—ฌ ํ•ด๋‹น ๊ตฌ๊ฐ„์—์„œ ์•ŒํŒŒ๋ฒณ์ด ๋“ฑ์žฅํ–ˆ๋Š”์ง€๋ฅผ ํŒŒ์•…ํ•˜๊ธฐ ์œ„ํ•ด ๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค๋ฅผ +1 ํ•ด์ฃผ์—ˆ๊ธฐ ๋–„๋ฌธ์ด๋‹ค.

๐Ÿ’ฌย ํ’€์ด

public func solution(_ S : inout String, _ P : inout [Int], _ Q : inout [Int]) -> [Int] {
    var a = Array(repeating: 0, count: S.count + 1)
    var c = Array(repeating: 0, count: S.count + 1)
    var g = Array(repeating: 0, count: S.count + 1)
    var t = Array(repeating: 0, count: S.count + 1)
    var ans: [Int] = []
    
    for (idx, i) in S.enumerated() {
        a[idx + 1] = a[idx]
        c[idx + 1] = c[idx]
        g[idx + 1] = g[idx]
        t[idx + 1] = t[idx]
        
        switch i {
        case "A":
            a[idx + 1] += 1
        case "C":
            c[idx + 1] += 1
        case "G":
            g[idx + 1] += 1
        default:
            t[idx + 1] += 1
            
        }
    }
    
    for i in 0..<P.count {
        if a[Q[i] + 1] - a[P[i]] > 0 {
            ans.append(1)
        } else if c[Q[i] + 1] - c[P[i]] > 0 {
            ans.append(2)
        } else if g[Q[i] + 1] - g[P[i]] > 0 {
            ans.append(3)
        } else {
            ans.append(4)
        }
    }
    
    return ans
}

์†Œ์š”์‹œ๊ฐ„ : 1์‹œ๊ฐ„ +

์‹œ๊ฐ„ ๋ณต์žก๋„ : O(N + M)

ํ‰๊ฐ€ํ‘œ : https://app.codility.com/demo/results/training7V4PMC-ED3/

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions