Find All Duplicates in an Array 算法复杂度O(n)的C++实现

问题详见:Find All Duplicates in an Array

      这是一道数组查找算法优化问题,题目问题描述如下:
     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~2次且 1a[i]n 的数组中找到出现2次的数组元素并输出。要求不使用额外空间,并使算法复杂度为 O(n)

解题思路:

      该题如果用普通的搜索算法能很容易找出符合要求的数组元素,但相应的其算法复杂度就变成了 O(n2) ,所以应当找到一个优化的算法使其算法复杂度为 O(n) 。所以想到可以在循环的同时对遇到的数组元素用其大小对应的位置的数进行标记,如果已经标记就说明该元素已经在之前扫描的时候的出现了一次,压进答案数组即可。而为了不使用额外的空间,又不影响原位置的数组元素本算法巧妙地使用相反数,将原来的正数变成负数进而达到标记目的。这样一来该算法就达到了不使用额外空间而且算法复杂度为 O(n) 。下面是具体的算法实现:

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

上面算法的提交运行结果如下:
提交结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值