Find All Duplicates in an Array问题及解法

来源:互联网 发布:韩国真实社会现状 知乎 编辑:程序博客网 时间:2024/06/01 09:54

问题描述:

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]
问题分析:

对于出现两次的元素,以它们的(值 - 1) 为索引所对应的另一个值是相同的,为了记录对应了两次,每对应依次就把该值取相反数即可。


过程详见代码:

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


原创粉丝点击