Formatted question description: https://leetcode.ca/all/1133.html

1133. Largest Unique Number

Level

Easy

Description

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

Solution

If the array has no elements, then there isn’t a largest integer, so return -1.

If the array has exactly 1 element, then the element is the largest integer that only occurs once, so return the integer.

Sort the array. Scan from the largest number to the smallest number. If the largest number only occurs once, return the largest number. Otherwise, if a number that is different to its both adjacent numbers is found, return the number. Otherwise, return the smallest number if it only occurs once, or return -1.

  • class Solution {
        public int largestUniqueNumber(int[] A) {
            if (A == null || A.length == 0)
                return -1;
            if (A.length == 1)
                return A[0];
            Arrays.sort(A);
            int length = A.length;
            if (A[length - 1] != A[length - 2])
                return A[length - 1];
            for (int i = length - 2; i > 0; i--) {
                int prevNum = A[i - 1], curNum = A[i], nextNum = A[i + 1];
                if (curNum != prevNum && curNum != nextNum)
                    return curNum;
            }
            if (A[0] != A[1])
                return A[0];
            else
                return -1;
        }
    }
    
  • Todo
    
  • print("Todo!")
    

All Problems

All Solutions