用 C++ 查找数组中的所有重复项
假设我们有一个整数数组,范围是 1 ≤ a[i] ≤ n(n = 数组的大小),其中一些元素出现两次,而另一些元素只出现一次。我们必须找出在此数组中出现两次的所有元素。所以,如果数组是 [4,3,2,7,8,2,3,1],则输出将是 [2, 3]
为解决这个问题,我们将按照以下步骤操作:
- n := 数组大小,创建一个名为 ans 的数组
- 对于 0 到 n – 1 范围内的 i
- x := nums[i] 的绝对值
- x 减去 1
- 如果 nums[x] < 0,则将 x + 1 添加到 ans 中,否则 nums[x] := nums[x] * (-1)
- 返回 ans
示例(C++)
让我们看看以下实现以加深理解:
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int n = nums.size();
vector <int> ans;
for(int i = 0; i < n; i++){
int x = abs(nums[i]);
x--;
if(nums[x] < 0) ans.push_back(x + 1);
else nums[x] *= -1;
}
return ans;
}
};
main(){
Solution ob;
vector<int> v = {4,3,2,7,8,2,3,1};
print_vector(ob.findDuplicates(v));
}输入
[4,3,2,7,8,2,3,1]
输出
[2,3]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP