Input: nums =[5,7,3,9,4,9,8,3,1]Output: 8Explanation: The maximum integer in the array is9 but it is repeated. The number 8 occurs only once, so it is the answer.
Example 2:
1
2
3
Input: nums =[9,9,8,8]Output: -1Explanation: There is no number that occurs only once.
classSolution {
public:int largestUniqueNumber(vector<int>& nums) {
unordered_map<int, int> cnt;
for (int n : nums) cnt[n]++;
int ans =-1;
for (auto& [n, c] : cnt) if (c ==1) ans = max(ans, n);
return ans;
}
};
1
2
3
4
5
6
7
funclargestUniqueNumber(nums []int) int {
cnt:=map[int]int{}
for_, n:=rangenums { cnt[n]++ }
ans:=-1forn, c:=rangecnt { ifc==1&&n > ans { ans = n } }
returnans}
1
2
3
4
5
6
7
8
9
classSolution {
publicintlargestUniqueNumber(int[] nums) {
Map<Integer, Integer> cnt =new HashMap<>();
for (int n : nums) cnt.put(n, cnt.getOrDefault(n, 0) + 1);
int ans =-1;
for (int n : cnt.keySet()) if (cnt.get(n) == 1 && n > ans) ans = n;
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funlargestUniqueNumber(nums: IntArray): Int {
val cnt = mutableMapOf<Int, Int>()
for (n in nums) cnt[n] = cnt.getOrDefault(n, 0) + 1var ans = -1for ((n, c) in cnt) if (c ==1&& n > ans) ans = n
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
deflargestUniqueNumber(self, nums: list[int]) -> int:
from collections import Counter
cnt = Counter(nums)
ans =-1for n, c in cnt.items():
if c ==1and n > ans:
ans = n
return ans
1
2
3
4
5
6
7
8
9
10
use std::collections::HashMap;
impl Solution {
pubfnlargest_unique_number(nums: Vec<i32>) -> i32 {
letmut cnt = HashMap::new();
for n in nums { *cnt.entry(n).or_insert(0) +=1; }
letmut ans =-1;
for (&n, &c) in&cnt { if c ==1&& n > ans { ans = n; } }
ans
}
}