1133. Largest Unique Number π
SourceBiweekly Contest 5 Q1DifficultyEasyRating1226
Description
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 <= 20000 <= nums[i] <= 1000
Solutions
Solution 1: Counting + Reverse Traversal
Thinking
We need the largest number that appears once, or \(-1\). Count frequencies, keep keys with count \(1\), and take the maximum. A fixed array of size \(1001\) scanned downward is the same idea when the range is tiny.
Given the data range in the problem, we can use an array of length \(1001\) to count the occurrence of each number. Then, we traverse the array in reverse order to find the first number that appears only once. If no such number is found, we return \(-1\).
The time complexity is \(O(n + M)\), and the space complexity is \(O(M)\). Here, \(n\) is the length of the array, and \(M\) is the maximum number that appears in the array. In this problem, \(M \leq 1000\).
1 2 3 4 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |