【数组】Leetcode编程题解:442. Find All Duplicates in an Array

来源:互联网 发布:散热分析中文软件 编辑:程序博客网 时间:2024/06/05 10:50

题目: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?
样例:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
这道题其实是上道题的改版,难度不大
提交代码:
# include < cstring >
class Solution {
public:
vector findDuplicates(vector& nums) {
int len = nums.size();
int result[len + 1];
memset(result, 0, sizeof(result));
for(int i = 0; i < len; i++) {
result[nums[i]]++;
}
vector ans;
for(int i = 0; i <= len; i++) {
if(result[i] == 2)
ans.push_back(i);
}
return ans;
}
};

0 0
原创粉丝点击