zoukankan      html  css  js  c++  java
  • 442. Find All Duplicates in an Array

    Problem:

    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]
    

    思路

    Solution (C++):

    vector<int> findDuplicates(vector<int>& nums) {
        if (nums.empty())  return vector<int>{};
        int n = nums.size();
        vector<int> res;
        
        for (int i = 0; i < n; ++i) {
            while (nums[i] != nums[nums[i]-1])  swap(nums[i], nums[nums[i]-1]);
        }
        for (int i = 0; i < n; ++i) {
            if (nums[i] != i+1)  res.push_back(nums[i]);
        }
        return res;
    }
    

    性能

    Runtime: 172 ms  Memory Usage: 12.5 MB

    思路

    Solution (C++):

    vector<int> findDuplicates(vector<int>& nums) {
        if (nums.empty())  return vector<int>{};
        int n = nums.size();
        vector<int> res;
        
        for (int i = 0; i < n; ++i) {
            nums[abs(nums[i])-1] = -nums[abs(nums[i])-1];
            if (nums[abs(nums[i])-1] > 0)  res.push_back(abs(nums[i]));
        }
        return res;
    }
    

    性能

    Runtime: 120 ms  Memory Usage: 12.7 MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    CF1070F Debate
    P3502 [POI2010]CHO-Hamsters
    CF1421A XORwice
    P2073 送花
    树链剖分边权转化为点权
    球——数学分析,模型构建
    数位dp的模版
    不要62
    智慧题——规律题
    CF551C GukiZ hates Boxes——模拟加二分
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12686915.html
Copyright © 2011-2022 走看看