442 Find all duplicates in an array of duplicate data

Source: Internet
Author: User
Tags array length

Given an integer array A, where 1≤a[i]≤n (n is an array length), where some elements occur two times and other elements appear once.
Find all elements that appear two times.
Can you solve this problem without going into any extra space and in O (n) time complexity?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
See: https://leetcode.com/problems/find-all-duplicates-in-an-array/description/

C++:

Method One:

Class Solution {public:    vector<int> findduplicates (vector<int>& nums) {        vector<int> res;        for (int i=0;i<nums.size (); ++i)        {            int idx=abs (nums[i])-1;            if (nums[idx]<0)            {                res.push_back (idx+1);            }            NUMS[IDX]=-NUMS[IDX];        }        return res;    }};

Method Two:

Class Solution {public:    vector<int> findduplicates (vector<int>& nums)    {        Vector<int > res;        for (int i = 0; i < nums.size (); ++i)        {            if (nums[i]! = Nums[nums[i]-1])            {                swap (nums[i], nums[nums[i] -1]);                -----;}        }        for (int i = 0; i < nums.size (); ++i)        {            if (nums[i]! = i + 1)            {                res.push_back (nums[i]);            }        }        return res;    }};

Reference: https://www.cnblogs.com/grandyang/p/6209746.html

442 Find all duplicates in an array of duplicate data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.