1133. 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

Rust Solution

struct Solution;

use std::collections::BTreeMap;

impl Solution {
    fn largest_unique_number(a: Vec<i32>) -> i32 {
        let mut btm: BTreeMap<i32, i32> = BTreeMap::new();
        for x in a {
            *btm.entry(x).or_default() += 1;
        }
        for (&k, &v) in btm.iter().rev() {
            if v == 1 {
                return k;
            }
        }
        -1
    }
}

#[test]
fn test() {
    let a = vec![5, 7, 3, 9, 4, 9, 8, 3, 1];
    assert_eq!(Solution::largest_unique_number(a), 8);
    let a = vec![9, 9, 8, 8];
    assert_eq!(Solution::largest_unique_number(a), -1);
}

Having problems with this solution? Click here to submit an issue on github.