Leetcode 442-Find All Duplicates in an Array

来源:互联网 发布:mac命令行终端 编辑:程序博客网 时间:2024/05/16 05:36

Given an array of integers, 1 ≤ a[i] ≤ n (n = size ofarray), 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]

 

题目的意思是给定一个长度为n的整数数组,数组中的元素1 ≤ a[i] ≤ n,有些元素出现一次,有些出现两次,让我们找出出现两次的元素。题目要求不开辟额外空间来实现时间复杂度O(n)的方法。


之前做过类似的题目,时间复杂度O(n),所以只能从头到尾遍历一次,不能做排序等操作。题目要求不能开辟额外空间,既然给定的数组中元素x都是介于1-n之间的,而数组正好也有n个元素,我们正好可以用a[x]的正负性来标记x是否出现过。将出现过一次的元素x,对应的a[x]标记为负。这题目的思路和 Leetcode 448. Find All NumbersDisappeared in an Array中的方法3思路很像,只不过448中我们是将出现过的元素x,对应的a[x]标记为负。

class Solution {public:    vector<int> findDuplicates(vector<int>& nums) {        vector<int>re;        for(int x:nums)        {            if(nums[abs(x)-1]<0)                re.push_back(abs(x));            else                nums[abs(x)-1]*=-1;        }        return re;    }};

 

原创粉丝点击