leetcode442 - Find All Duplicates in an Array - medium
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之间,duplicates只会出现两次。做一个简单转换,对于每个数num,遍历到它的时候我们对index为num-1的数取相反数。如果碰到某个index上的数是负的了,那就说明之前遇到过这个index所对应的num了。注意因为某些数会被操作过,取值的时候要取绝对值。
实现:
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> res; for (int num : nums){ if (nums[abs(num)-1] < 0) res.push_back(abs(num)); else nums[abs(num)-1] *= -1; } return res; } };

浙公网安备 33010602011771号