comments | difficulty | edit_url | rating | source | tags | |||
---|---|---|---|---|---|---|---|---|
true |
Easy |
1226 |
Biweekly Contest 5 Q1 |
|
Given an integer array nums
, return the largest integer that only occurs once. If no integer occurs once, return -1
.
Example 1:
Input: nums = [5,7,3,9,4,9,8,3,1] Output: 8 Explanation: The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it is the answer.
Example 2:
Input: nums = [9,9,8,8] Output: -1 Explanation: There is no number that occurs only once.
Constraints:
1 <= nums.length <= 2000
0 <= nums[i] <= 1000
Given the data range in the problem, we can use an array of length
The time complexity is
class Solution:
def largestUniqueNumber(self, nums: List[int]) -> int:
cnt = Counter(nums)
return max((x for x, v in cnt.items() if v == 1), default=-1)
class Solution {
public int largestUniqueNumber(int[] nums) {
int[] cnt = new int[1001];
for (int x : nums) {
++cnt[x];
}
for (int x = 1000; x >= 0; --x) {
if (cnt[x] == 1) {
return x;
}
}
return -1;
}
}
class Solution {
public:
int largestUniqueNumber(vector<int>& nums) {
int cnt[1001]{};
for (int& x : nums) {
++cnt[x];
}
for (int x = 1000; ~x; --x) {
if (cnt[x] == 1) {
return x;
}
}
return -1;
}
};
func largestUniqueNumber(nums []int) int {
cnt := [1001]int{}
for _, x := range nums {
cnt[x]++
}
for x := 1000; x >= 0; x-- {
if cnt[x] == 1 {
return x
}
}
return -1
}
function largestUniqueNumber(nums: number[]): number {
const cnt = Array(1001).fill(0);
for (const x of nums) {
++cnt[x];
}
for (let x = 1000; x >= 0; --x) {
if (cnt[x] === 1) {
return x;
}
}
return -1;
}
/**
* @param {number[]} nums
* @return {number}
*/
var largestUniqueNumber = function (nums) {
const cnt = Array(1001).fill(0);
for (const x of nums) {
++cnt[x];
}
for (let x = 1000; x >= 0; --x) {
if (cnt[x] === 1) {
return x;
}
}
return -1;
};