1207. Unique Number of Occurrences (使用 C 語言解題)

Easy
Topics
Companies
Hint

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

google 翻譯:

給定一個整數數組 arr,如果數組中每個值出現的次數唯一,則傳回 true,否則傳回 false



想法一:

分兩個 hash 陣列,
第一個 hash1 存放傳入的 arr 陣列數值個數,
第二個 hash2 存放個數是否唯一。

寫法一:

bool uniqueOccurrences(int* arr, int arrSize) {
int *hash = calloc(2001, sizeof(int)); // 存放傳入的 arr 陣列數值個數
int *hash2 = calloc(2001, sizeof(int)); // 存放個數是否唯一
bool result = true;
// 將傳入的 arr 陣列數值轉化為個數
for(int i=0; i<arrSize; i++) {
hash[arr[i] + 1000]++;
}
// 檢視 hash
for(int i=0; i<2001; i++) {
if(hash[i] == 0) // 數值沒出現過,就看下一個
continue;
if(hash2[hash[i]] > 0) // 判斷個數是否唯一
return false;
if(hash[i] > 0) // 數值有出現
hash2[hash[i]]++; // 數值個數的個數+1
}
return true;
}

結果一:
結果很棒哦~



沒有留言:

張貼留言