publicclassSolution { publiccharSlowestKey(int[] releaseTimes, string keysPressed) { int n = releaseTimes.Length; char ans = keysPressed[0]; int maxTime = releaseTimes[0]; for (int i = 1; i < n; i++) { char key = keysPressed[i]; int time = releaseTimes[i] - releaseTimes[i - 1]; if (time > maxTime || (time == maxTime && key > ans)) { ans = key; maxTime = time; } } return ans; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: charslowestKey(vector<int>& releaseTimes, string keysPressed){ int n = releaseTimes.size(); char ans = keysPressed[0]; int maxTime = releaseTimes[0]; for (int i = 1; i < n; i++) { char key = keysPressed[i]; int time = releaseTimes[i] - releaseTimes[i - 1]; if (time > maxTime || (time == maxTime && key > ans)) { ans = key; maxTime = time; } } return ans; } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13
charslowestKey(int* releaseTimes, int releaseTimesSize, char * keysPressed){ char ans = keysPressed[0]; int maxTime = releaseTimes[0]; for (int i = 1; i < releaseTimesSize; i++) { char key = keysPressed[i]; int time = releaseTimes[i] - releaseTimes[i - 1]; if (time > maxTime || (time == maxTime && key > ans)) { ans = key; maxTime = time; } } return ans; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13
funcslowestKey(releaseTimes []int, keysPressed string)byte { ans := keysPressed[0] maxTime := releaseTimes[0] for i := 1; i < len(keysPressed); i++ { key := keysPressed[i] time := releaseTimes[i] - releaseTimes[i-1] if time > maxTime || time == maxTime && key > ans { ans = key maxTime = time } } return ans }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: defslowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: ans = keysPressed[0] maxTime = releaseTimes[0] for i inrange(1, len(keysPressed)): key = keysPressed[i] time = releaseTimes[i] - releaseTimes[i - 1] if time > maxTime or time == maxTime and key > ans: ans = key maxTime = time return ans
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var slowestKey = function(releaseTimes, keysPressed) { const n = releaseTimes.length; let ans = keysPressed[0]; let maxTime = releaseTimes[0]; for (let i = 1; i < n; i++) { const key = keysPressed[i]; const time = releaseTimes[i] - releaseTimes[i - 1]; if (time > maxTime || (time === maxTime && key > ans)) { ans = key; maxTime = time; } } return ans; };
复杂度分析
时间复杂度:O(n),其中 n 是数组 releaseTimes 和字符串 keysPressed 的长度。需要同时遍历数组和字符串一次。