LeetCode Solution, Easy, 1629. Slowest Key

尋找最慢的 Key

1629. Slowest Key

題目敘述

A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.

You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.

The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].

Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.

Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.

Example 1:

Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
Output: "c"
Explanation: The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.

Example 2:

Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
Output: "a"
Explanation: The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.

Constraints:

  • releaseTimes.length == n
  • keysPressed.length == n
  • 2 <= n <= 1000
  • 1 <= releaseTimes[i] <= 109
  • releaseTimes[i] < releaseTimes[i+1]
  • keysPressed contains only lowercase English letters.

Hint 1:

Get for each press its key and amount of time taken.

Hint 2:

Iterate on the presses, maintaining the answer so far.

Hint 3:

The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.

題目翻譯

給一個字串 keysPressed 和一個排序過的佇列 releaseTimes。其中相同的 keysPressed 的字母會重複。相同索引下,releaseTimes 的值會表示當前執行時間。

解法解析

這題的解法,是使用基本的 Dyanmic programming 的方式。每一次迴圈裡面去計算最慢的 key,有點類似 JavaScript 中 reduce 的功能。 也因為只有用一個迴圈處理,所以 Time complexity 只有 O(n),而只要用一個變數儲存目前的最慢的 key,所以 Space complexity 只有 O(1)

程式範例

Python
class Solution:
    def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
        n = len(releaseTimes)
        max_diff = releaseTimes[0]
        result = keysPressed[0]

        for i in range(1, n):
            diff = releaseTimes[i] - releaseTimes[i-1]
            if diff > max_diff or (diff == max_diff and keysPressed[i] > result):
                max_diff = diff
                result = keysPressed[i]

        return result
JavaScript
/**
 * @param {number[]} releaseTimes
 * @param {string} keysPressed
 * @return {character}
 */
var slowestKey = function (releaseTimes, keysPressed) {
    const n = releaseTimes.length;
    let maxDiff = releaseTimes[0];
    let result = keysPressed[0];

    for (let i = 1; i < n; i++) {
        const diff = releaseTimes[i] - releaseTimes[i - 1];
        if (
            diff > maxDiff ||
            (diff === maxDiff && keysPressed[i] > result)
        ) {
            maxDiff = diff;
            result = keysPressed[i];
        }
    }

    return result;
};
Go
func slowestKey(releaseTimes []int, keysPressed string) byte {
    n := len(releaseTimes)
    result := keysPressed[0]
    maxDiff := releaseTimes[0]

    for i := 1; i < n; i++ {
        diff := releaseTimes[i] - releaseTimes[i-1]
        if diff > maxDiff || (diff == maxDiff && keysPressed[i] > result) {
            maxDiff = diff
            result = keysPressed[i]
        }
    }

    return result
}
Swift

```swiftclass Solution { func slowestKey( releaseTimes: [Int], keysPressed: String) -> Character { let keysPressed = Array(keysPressed) var result = Character("?"), maxDiff = Int.min, lastTime = 0

    for i in 0..<keysPressed.count {
        let diff = releaseTimes[i] - lastTime
        lastTime = releaseTimes[i]
        if diff > maxDiff || diff == maxDiff && keysPressed[i] > result {
            maxDiff = diff
            result = keysPressed[i]
        }
    }
    return result
}

}


##### Kotlin

```kotlin
class Solution {
    fun slowestKey(releaseTimes: IntArray, keysPressed: String): Char {
        var result = keysPressed[0]
        var maxDiff = releaseTimes[0]
        var index = 1

        while (index < keysPressed.length) {
            val currentSymbol = keysPressed[index]
            val diff = releaseTimes[index] - releaseTimes[index - 1]

            if (diff > maxDiff || (diff == maxDiff && currentSymbol > result)) {
                maxDiff = diff
                result = currentSymbol
            }

            index++
        }

        return result
    }
}

Did you find this article valuable?

Support 攻城獅 by becoming a sponsor. Any amount is appreciated!