Leetcode 442. Find all duplicates in an array (finds all duplicates in the array)

Source: Internet
Author: User

Given an array of integers, 1≤a[i]≤ n (n = size of array), some elements appear twice and others AppE AR once.

Find all the elements, appear twice in this array.

Could do it without extra space and in O (n) runtime?

Example:

input:[4,3,2,7,8,2,3,1]output:[2,3]

Title tag: The array topic gives us a nums array with some numbers appearing two times and the rest appearing only once, allowing us to find all the repetitions two times. Because this topic does not stipulate that we cannot change the array, we can map num in array to nums[Num-1] one-to-two mappings, and each time we encounter a num, we change the corresponding position num to the-num mark. If you encounter a duplicate, it must have been tagged with the same number.

Java Solution:

Runtime beats 85.92%

Completion Date: 09/19/2017

Keywords: Array

Key point: Make Num and num[num-1] 1-to-1 mappings

1 classSolution2 {3      PublicList<integer> Findduplicates (int[] nums)4     {5List<integer> duplicates =NewArraylist<>();6         7          for(intnum:nums)8         {9             intAbsnum =math.abs (num);Ten              One             if(Nums[absnum-1] < 0)//If the number at position num-1 is already negative ADuplicates.add (Absnum);//num is duplicate -             Else -NUMS[ABSNUM-1] *=-1; the         } -          -         returnduplicates; -     } +}

Resources:

Https://discuss.leetcode.com/topic/64735/java-simple-solution

Leetcode List of topics- leetcode Questions List

Leetcode 442. Find all duplicates in an array (finds all duplicates in the array)

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.