题目:
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
翻译:
1~n中一些数组成了长度为n的数组,其中一些数出现2遍,一些1遍,一些没出现,找出出现两遍的数。
解答:
(94.96%)
vector<int> findDuplicates(vector<int>& nums) {
int n = nums.size();
vector<int> s(n, 0);//初始化为0
vector<int> a;
for (int i = 0; i<n; i++){
if (s[nums[i] - 1] == 1)
a.push_back(nums[i]);//是1,说明是第二次出现,加入到a中。
else
s[nums[i] - 1] = 1;//第一次出现,设置为1。
}
return a;
}
注意:
学会使用标记:给几类数定义符号