LeetCode //C - 1207. Unique Number of Occurrences

1207. Unique Number of Occurrences

Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
 

Example 1:

Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.

Example 2:

Input: arr = [1,2]
Output: false

Example 3:

Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true

Constraints:
  • 1 <= arr.length <= 1000
  • -1000 <= arr[i] <= 1000

From: LeetCode
Link: 1207. Unique Number of Occurrences


Solution:

Ideas:

We can use a hash table (or an array, considering the constraints) to count occurrences. Then, we use another hash table to check for the uniqueness of these counts.

  • occurrences is an array indexed from -1000 to 1000 (shifted by 1000 to accommodate negative numbers), used to count the occurrences of each integer in arr.
  • seen is a boolean array used to track if a specific occurrence count has been seen before.
  • We first iterate through the arr to count the occurrences of each number.
  • Then, we iterate through the occurrences array to check if any count has been seen before. If a count is repeated, we return false. If we finish the loop without finding any duplicate counts, we return true.
Code:
bool uniqueOccurrences(int* arr, int arrSize) {
    int occurrences[2001] = {0}; // Array to count occurrences, offset by 1000 for negative numbers
    bool seen[1001] = {false}; // Array to track if an occurrence count has been seen

    // Count occurrences of each number
    for (int i = 0; i < arrSize; i++) {
        occurrences[arr[i] + 1000]++;
    }

    // Check for unique occurrences
    for (int i = 0; i < 2001; i++) {
        if (occurrences[i] > 0) {
            if (seen[occurrences[i]]) {
                // If we have already seen this count, it's not unique
                return false;
            }
            seen[occurrences[i]] = true;
        }
    }

    return true;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值