the first one in Biweekly Contest 48.
Difficulty : Easy
Related Topics : String
Given an alphanumeric string
s
, return the second largest numerical digit that appears ins
, or-1
if it does not exist.An alphanumeric string is a string consisting of lowercase English letters and digits.
Input: s = "dfa12321afd" Output: 2 Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
Input: s = "abc1111" Output: -1 Explanation: The digits that appear in s are [1]. There is no second largest digit.
1 <= s.length <= 500
s
consists of only lowercase English letters and/or digits.
- mine
- Java
Runtime: 1 ms, faster than 100.00%, Memory Usage: 39.3 MB, less than 100.00% of Java online submissions
// O(N)time // O(N)space public int secondHighest(String s) { char[] arr = s.toCharArray(); int size = 0; int[] count = new int[10]; for(int i = 0; i < arr.length; i++){ if(arr[i] >= 'a') continue; int t = arr[i] - '0'; if(count[t] == 0) size++; count[t]++; } if(size < 2) return -1; int t = 2; for(int i = count.length - 1; i >= 0; i--){ if(count[i] != 0){ t--; } if(t == 0) return i; } return 0; }
- Java