442 Find all duplicates in an array

这篇博客介绍了两种解决在给定长度为n的整数数组中找出所有出现两次的整数的方法。第一种方法利用位操作,通过将正负号用来标记元素出现次数,当遇到一个元素时,将其对应的位取反,第二次遇到时就会发现其已变为负数。第二种方法使用哈希表,遍历数组时将元素作为键,如果已存在则将该元素添加到结果中,否则将其值设为1。两种方法都在O(n)时间内完成并只使用了常数额外空间。示例输入为[4,3,2,7,8,2,3,1],输出为[2,3]。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The description of problem

Given an integer array nums of length n where all the integers of nums are in the range [1, n] 
and each integer appears once or twice, return an array of all the integers that appears twice.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-duplicates-in-an-array

an example

Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]

Solution 1

intuition

use positive and negative signs to indicate the appearance times for a specific element.
specifically, when you just found a elements nums[i], we could use minus sign add to the nums[nums[i] - 1]
easily to see, when you just found the second elements in your array, you will do the above operation once again.

The codes

#include <vector>
#include <iostream>
#include <cmath>
using namespace std;
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
		vector<int> res;
		for (auto num : nums) {
			int flag_pos = abs(num) - 1;
			if (nums[flag_pos] < 0) {
				res.push_back(abs(num));
			} else {
				nums[flag_pos] = -nums[flag_pos];
			}
		}
		return res;
    }
};
int main() 
{
	Solution s;
	vector<int> nums = {4,3,2,7,8,2,3,1};
	vector<int> res = s.findDuplicates(nums);
	for (int i = 0; i < res.size(); i++) {
		cout << res[i] << " ";
	}
	cout << endl;
}

The corresponding results

2 3

The solution 2

The intuition

use the data structure of map to find the elements appearing twice in the array

The codes

#include <vector>
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
		vector<int> res;
		// initialize a hash table with 0
		unordered_map<int, int> hash;
		for (auto num : nums) {
			if (hash[num] == 1) {
				res.emplace_back(num);
			} else {
				hash[num] = 1;
			}
		}
		return res;
		
    }
};
int main() 
{
	Solution s;
	vector<int> nums = {4,3,2,7,8,2,3,1};
	vector<int> res = s.findDuplicates(nums);
	for (int i = 0; i < res.size(); i++) {
		cout << res[i] << " ";
	}
	cout << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值