/*
* @lc app=leetcode id=442 lang=cpp
*
* [442] Find All Duplicates in an Array
*/
// @lc code=start
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int N = nums.size();
int M = N + 1;
int t;
for(int i=0;i<N;i++){
t = nums[i]%M - 1;
nums[t] += M;
}
vector<int> ans;
for(int i=0;i<N;i++){
t = nums[i]/M;
if(t > 1) ans.push_back(i+1);
}
return ans;
}
};
// @lc code=end
No.253 - [442] Find All Duplicates in an Array - 下标来hash
最新推荐文章于 2025-12-05 21:56:57 发布
本文介绍了一种使用C++实现的高效算法,该算法用于找出数组中所有重复出现的元素。通过对数组进行一次遍历,并利用数组自身作为哈希表来标记已访问过的元素,从而在O(n)的时间复杂度内解决问题。
3万+

被折叠的 条评论
为什么被折叠?



