Find All Duplicates in an Array

来源:互联网 发布:国别域名注册 编辑:程序博客网 时间:2024/06/02 09:41

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, 从这个点出发来想,遍历当前位置的值时,找到这个值位置的值做标记,不多说了,看代码

代码:

class Solution {public:    vector<int> findDuplicates(vector<int>& nums) {        vector<int>ans;        for (int i=0; i<nums.size(); i++)        {            int index=abs(nums[i])-1;            if (nums[index]<0)            {                ans.push_back(index+1);            }            nums[index]=-1*nums[index];        }        return ans;            }};




0 0
原创粉丝点击