Skip to content

Latest commit

 

History

History
112 lines (78 loc) · 2.04 KB

File metadata and controls

112 lines (78 loc) · 2.04 KB

中文文档

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

Solutions

Python3

class Solution:
    def largestUniqueNumber(self, A: List[int]) -> int:
        counter = collections.Counter(A)
        for i in range(1000, -1, -1):
            if counter[i] == 1:
                return i
        return -1

Java

class Solution {
    public int largestUniqueNumber(int[] A) {
        int[] counter = new int[1001];
        for (int a : A) {
            ++counter[a];
        }
        for (int i = 1000; i >= 0; --i) {
            if (counter[i] == 1) {
                return i;
            }
        }
        return -1;
    }
}

JavaScript

/**
 * @param {number[]} A
 * @return {number}
 */
var largestUniqueNumber = function (A) {
  let counter = {};
  for (const a of A) {
    counter[a] = (counter[a] || 0) + 1;
  }
  for (let i = 1000; i >= 0; --i) {
    if (counter[i] == 1) {
      return i;
    }
  }
  return -1;
};

...