LeetCode 1133. Largest Unique Number

Description

https://leetcode.com/problems/largest-unique-number/

Given an array of integers A, return the largest integer that only occurs once.

If no integer occurs once, return -1.

Example 1:

Input: [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's the answer.

Example 2:

Input: [9,9,8,8]
Output: -1
Explanation: 
There is no number that occurs only once.

Note:

  1. 1 <= A.length <= 2000
  2. 0 <= A[i] <= 1000

Explanation

Count, sort, and find out the result.

Python Solution

class Solution:
    def largestUniqueNumber(self, A: List[int]) -> int:
        counter = {}
        
        for num in A:
            counter[num] = counter.get(num, 0) + 1
            
        results = []
        for key, value in counter.items():
            if value == 1:
                results.append(key)
        
        if not results:
            return -1
        
        results = sorted(results)
        
        return results[-1]
  • Time Complexity: O(N)
  • Space Complexity: O(Nlog(N))

Leave a Reply

Your email address will not be published. Required fields are marked *