dimanche 19 janvier 2020

Why did removing "else" without changing logic cut my runtime in half?

After solving this problem on LeetCode: https://leetcode.com/problems/count-and-say/ my first solution took 16ms. By removing an else statement, without (as far as I can tell) changing the logic in any way, the runtime went down to 8ms.

It went from beating 24.31% of swift submissions to beating 93.75%.

Can anyone explain why? It feels to me like they should be the same.

func countAndSay(_ n: Int) -> String {
    if n == 1 {
        return "1"
    }

    var output = ""
    let previous = countAndSay(n-1)

    var count = 0
    var lastChar = Character("0")

    for (n, c) in previous.enumerated() {           
        if n == 0 {
            lastChar = c
            count = 1
        } else {
            if c == lastChar {
                count += 1
            } else {
                output += "\(count)\(lastChar)"
                count = 1
                lastChar = c
            }
        }
    }

    output += "\(count)\(lastChar)"

    return output
}

I changed the for loop to this and cut the time in half:

for (n, c) in previous.enumerated() {
        if n == 0 {
            lastChar = c
            count = 1
            continue
        }

        if c == lastChar {
            count += 1
        } else {
            output += "\(count)\(lastChar)"
            count = 1
            lastChar = c
        }
    }

Aucun commentaire:

Enregistrer un commentaire