1207. Unique Number of Occurrences*

1207. Unique Number of Occurrences*

https://leetcode.com/problems/unique-number-of-occurrences/

题目描述

Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.

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

C++ 实现 1

判断每个元素出现的个数是不是 unique 的.

使用两个哈希表, 一个记录每个元素的个数, 另一个判断是否出现的个数是 unique 的.

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        unordered_map<int, int> record;
        unordered_set<int> nums;
        for (auto &c : arr)
            record[c] ++;
        for (auto &p : record) {
            if (nums.count(p.second)) return false;
            nums.insert(p.second);
        }
        return true;
    }
};

C++ 实现 2

或者这样写, 来自 LeetCode Submission

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
	  unordered_map<int, int> m;
	  unordered_set<int> s;
	  for (auto n : arr) ++m[n];
	  for (auto& p : m) s.insert(p.second);
	  return m.size() == s.size();
	}
};
发布了394 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104745404
今日推荐