The number of duplicates in the array of offer 50

Source: Internet
Author: User

First, the topic

All numbers in an array of length n are within the range of 0 to n-1. Some of the numbers in the array are duplicates, but it is not known that several numbers are duplicates. I don't know how many times each number repeats. Please find any duplicate numbers in the array. For example, if you enter an array of length 7 {2,3,1,0,2,5,3}, the corresponding output is the first repeating number 2.

Second, the idea

Solution One: the solution using Linkedhashmap

Solution Two: See the code (recommended)

Third, the Code

Solution One:

 Packagecn1;ImportJava.util.LinkedHashMap;ImportJava.util.Map;ImportJava.util.Set; Public classSolution { Public BooleanDuplicateintNumbers[],intLengthint[] duplication) {        Booleanflag=false; if(numbers==NULL|| Length==0){            returnFlag; }        //count the number of strings, pay attention to using LinkedhashmapLinkedhashmap<integer, integer> lhm =NewLinkedhashmap<integer, integer>();  for(intnum:numbers) {            if(Lhm.containskey (num)) {lhm.put (num, lhm.get (num)+ 1); } Else{lhm.put (num,1); }        }        //Traverse Map to find the first occurrence of a number        intVal=-1; Set<Map.Entry< Integer, integer>> set =Lhm.entryset ();  for(map.entry< Integer, integer>Es:set) {            intKey =Es.getkey (); intValue =Es.getvalue (); if(Value >= 2) {Val=key;  Break; }        }        if(Val!=-1) {duplication[0]=Val; Flag=true; }        //return Results        returnFlag; }}
View Code

Solution Two:

 Public BooleanDuplicateintNumbers[],intLengthint[] duplication) {        Boolean[] k =New Boolean[length];  for(inti = 0; i < k.length; i++) {            if(K[numbers[i]] = =true) {duplication[0] =Numbers[i]; return true; } K[numbers[i]]=true; }        return false;}
View Code

---------------------------------------------

Reference Links:

Https://www.nowcoder.com/questionTerminal/623a5ac0ea5b4e5f95552655361ae0a8

The number of duplicates in the array of offer 50

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.