🤔

2021/12/04に公開

# Question

``````Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.

An alphanumeric string is a string consisting of lowercase English letters and digits.
``````

# Code

``````class Solution {
fun secondHighest(s: String): Int {

val ss = s.filter { it in '0'..'9' }.map { it.toString().toInt() }.toSet()
if (ss.size < 2) return -1
return ss.sortedDescending()[1]
}
}
``````
``````class Solution {
fun secondHighest(s: String): Int {
var largest = -1
var second = -2

val ssets = s.toSet()
for (digit in ssets) {
digit.toString().toIntOrNull()?.let {
when {
it > largest -> {
second = largest
largest = it
}
it == largest -> {}
it in second until largest -> {
second = it
}
else -> {}
}
}
}
return if (largest == -1 || second == -2) -1 else second
}
}
``````

あまりアルゴリズム的なアプローチが光るような問題ではなかったので、個人的には1つ目ので十分な気がしている...
Setにはしたほうがいいと思う

# Profile

• 1つ目
• Runtime: 204 ms
• Memory Usage: 37.5 MB
• 2つ目
• Runtime: 172 ms
• Memory Usage: 35.8 MB

GitHubで編集を提案