961.在长度2N的数组中找出重复N次的元素
链接:961.在长度2N的数组中找出重复N次的元素
难度:Easy
标签:数组、哈希表
简介:找出并返回重复了 n 次的那个元素。
题解 1 - cpp
- 编辑时间:2022-03-25
- 执行用时:20ms
- 内存消耗:24.1MB
- 编程语言:cpp
- 解法介绍:查找某个元素的出现次数是否大于 1。
class Solution {
public:
int repeatedNTimes(vector<int>& nums) {
int m[10004] = {0};
for (auto& num : nums) {
if (++m[num] > 1) return num;
}
return 0;
}
};
题解 2 - cpp
- 编辑时间:2022-05-21
- 执行用时:28ms
- 内存消耗:24.1MB
- 编程语言:cpp
- 解法介绍:随机选择,只有目标数是重复的。
class Solution {
public:
int repeatedNTimes(vector<int> &nums) {
srand(time(0));
int n = nums.size();
while (1) {
int x = rand() % n, y = rand() % n;
if (x != y && nums[x] == nums[y]) return nums[x];
}
return -1;
}
};