• 442. 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]
    思路:
      这道题需要我们在一个大小为n的数组中,每一个元素的取值范围为[1,n],然后找其中重复的元素,要求不能使用额外的空间,需要在线性时间复杂度内完成。
      解决该问题的基本思路很简单:
    • 类似于哈希的形式,将数字i放在第i-1个元素,即a[i-1] = i,i的取值范围为[1,n]
    • 如果数组中没有重复,那么经过这样的调整,得到的数组应该是[1,2,3...n],这个时候不存在重复的元素
    • 一旦出现了重复的元素,意味着有些数组元素与数字对应不上。比如a= [4,3,2,7,8,2,3,1]经过了上面的变换,变成了[1,2,3,4,3,2,7,8]由于2与3的重复,导致了5,6的缺失,因此在a[4],a[5]上的值是不等于5和6的
    •  所以,在经历了变换之后,只需要将“元素与数字对应不上”的数字挑出来就可以得到答案了

      关键在于,如何进行这个变换:用一个计数器i,初始化为0。当a[i]与a[a[i]-1]相等时,计数器递增(因为找到了对应的元素和数字了),如果不是的话,就交换a[i]与a[a[i]-1]

    代码:

    class Solution {
    public:
        vector<int> findDuplicates(vector<int>& nums) {
            int n = nums.size();
            vector<int> res;
            for (int i = 0 ; i < n ;)
            {
                if(nums[i] != nums[nums[i]-1])
                    swap(nums[i],nums[nums[i]-1]);
                else i++;
            }
            
            for(int i = 0 ; i < n ; i++)
                if(nums[i]!=i+1)
                    res.push_back(nums[i]);
            
            return res;
        }
    };
  • 相关阅读:
    Django基础之cookie
    Django基础之redirect()
    Django基础之render()
    Django基础之JsonResponse对象
    Django基础之response对象
    scrapy框架自定制命令
    数据分析案例-拉勾网招聘信息
    爬虫之单线程多任务异步抓取
    数据分析之matplotlib使用
    数据分析之numpy使用
  • 原文地址:https://www.cnblogs.com/MT-ComputerVision/p/6946293.html
Copyright © 2020-2023  润新知