[leetcode] 442. Find All Duplicates in an Array
程序员文章站
2024-02-17 11:41:34
...
题目:
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]
代码:
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
for(int i = 0; i < nums.size(); i++){
int index = abs(nums[i]) - 1;
if(nums[index] > 0){
nums[index] = -nums[index];
}else{
nums[index] = -nums[index];
res.push_back(index+1);
}
}
return res;
}
};
推荐阅读
-
[leetcode] 442. Find All Duplicates in an Array
-
【LeetCode】442. Find All Duplicates in an Array(找出数组中的重复项)
-
[leetcode] 442. Find All Duplicates in an Array
-
leetcode 442. Find All Duplicates in an Array
-
【一天一道LeetCode】#26. Remove Duplicates from Sorted Array
-
LeetCode448 — Find All Numbers Disappeared in an Array
-
LeetCode442 — Find All Duplicates in an Array
-
leetcode 448. Find All Numbers Disappeared in an Array
-
LeetCode-448. Find All Numbers Disappeared in an Array
-
Leetcode 448. Find All Numbers Disappeared in an Array (python+cpp)