Skip to content

442. Find All Duplicates in an Array #335

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
namespace-io opened this issue Aug 16, 2019 · 0 comments
Open

442. Find All Duplicates in an Array #335

namespace-io opened this issue Aug 16, 2019 · 0 comments

Comments

@namespace-io
Copy link
Owner

交换一下

class Solution {
public:
    vector<int> findDuplicates(vector<int>& a) {
        int n = a.size();
        for(int i = 0; i < n; i++){
            while(i != a[i]-1 && a[a[i]-1] != a[i]) swap(a[a[i]-1], a[i]);
        }
        
        vector<int> ret;
        for(int i = 0; i < n; i++){
            if(i != a[i] - 1) ret.push_back(a[i]);
        }
        
        return ret;
    }
};

将遇到a[idx]就翻转,如果为负,说明之前有重复的。

class Solution {
public:
    vector<int> findDuplicates(vector<int>& a) {
        int n = a.size();
        vector<int> ret;
        for(int i = 0; i < n; i++){
            int idx = abs(a[i]) - 1;
            if(a[idx] < 0) ret.push_back(idx + 1);
            a[idx] = -a[idx];
        }

        return ret;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant