返回介绍

solution / 1100-1199 / 1133.Largest Unique Number / README_EN

发布于 2024-06-17 01:03:23 字数 3803 浏览 0 评论 0 收藏 0

1133. Largest Unique Number

中文文档

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 <= 2000
  • 0 <= nums[i] <= 1000

Solutions

Solution 1: Counting + Reverse Traversal

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

class Solution:
  def largestUniqueNumber(self, nums: List[int]) -> int:
    cnt = Counter(nums)
    return next((x for x in range(1000, -1, -1) if cnt[x] == 1), -1)
class Solution {
  public int largestUniqueNumber(int[] nums) {
    int[] cnt = new int[1001];
    for (int x : nums) {
      ++cnt[x];
    }
    for (int x = 1000; x >= 0; --x) {
      if (cnt[x] == 1) {
        return x;
      }
    }
    return -1;
  }
}
class Solution {
public:
  int largestUniqueNumber(vector<int>& nums) {
    int cnt[1001]{};
    for (int& x : nums) {
      ++cnt[x];
    }
    for (int x = 1000; ~x; --x) {
      if (cnt[x] == 1) {
        return x;
      }
    }
    return -1;
  }
};
func largestUniqueNumber(nums []int) int {
  cnt := [1001]int{}
  for _, x := range nums {
    cnt[x]++
  }
  for x := 1000; x >= 0; x-- {
    if cnt[x] == 1 {
      return x
    }
  }
  return -1
}
function largestUniqueNumber(nums: number[]): number {
  const cnt = new Array(1001).fill(0);
  for (const x of nums) {
    ++cnt[x];
  }
  for (let x = 1000; x >= 0; --x) {
    if (cnt[x] == 1) {
      return x;
    }
  }
  return -1;
}
/**
 * @param {number[]} nums
 * @return {number}
 */
var largestUniqueNumber = function (nums) {
  const cnt = new Array(1001).fill(0);
  for (const x of nums) {
    ++cnt[x];
  }
  for (let x = 1000; x >= 0; --x) {
    if (cnt[x] == 1) {
      return x;
    }
  }
  return -1;
};

Solution 2

class Solution:
  def largestUniqueNumber(self, nums: List[int]) -> int:
    cnt = Counter(nums)
    return max((x for x, v in cnt.items() if v == 1), default=-1)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文