题目: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;
}
};
【数组】Leetcode编程题解:442. Find All Duplicates in an Array
最新推荐文章于 2019-10-31 21:04:37 发布