A number of more than half occurrences in a offer-array.

Source: Internet
Author: User

After the test, finish the lesson set to continue to do the problem.

Title: More than half occurrences of numbers in an array

Title Description: There is a number in the array that appears more than half the length of the array, please find this number. For example, enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array 5 times, which exceeds half the length of the array, the output is 2. Output 0 If it does not exist.

Thought analysis: The sword refers to the offer on the question feel is not difficult, I actually want to do that can think for a long, the final thought of the answer, the answer is very ingenious that kind of question. The question is nothing more than a study of language features or a little bit of data structure, and there are many ways to do this.

method One: The use of arrays combined with the topic Requirements for analysis, in fact, the problem is to give you an array, to see if there is such a number, it is larger than the number of all the elements in the array of half, some words on the output of this number, no words on the output 0. If this number is present, it will occur more often than all other numbers. Since the array itself is unordered, the arrays are traversed, and two values are saved when iterating over the array: One is a number in the array, and the other is the number of times. When traversing the next number, if it is the same as the previously saved number, the number of times is 1, otherwise the number is reduced by 1, and if the number is 0, the next number is saved and the number is set to 1. After the traversal is completed, the saved numbers are the desired. Then judge if it meets the criteria. Because only the array is traversed, the time complexity is O (n)

The code is as follows:

1  Public classSolution {2      Public intMorethanhalfnum_solution (int[] Array) {3         if(array.length==0)return0;4         intCount=1,num=array[0];5          for(inti=1;i<array.length;i++){6             if(Array[i]==num) count++;7             Elsecount--;8             if(count==0){9num=Array[i];TenCount=1; One             }           A         } -Count=0; -          for(inti=0;i<array.length;i++){ the             if(Array[i]==num) count++; -         } -         if(count*2>array.length) { -             returnnum; +         } -         Else return0; +     } A}

Method Two: Because the array itself is unordered, then I can also sort to get the results I want, Java comes with the sort method to sort the array, it uses the idea of a fast line, so the time complexity is O (NLOGN)

If there is such a number, then, after I sort, in the middle position of the array must have it, then I already know this number, just to ask for the number of occurrences of the verification can be

The code is as follows:

1 Importjava.util.Arrays;2  3  Public classSolution {4 Public intMorethanhalfnum_solution (int[] Array) {5 Arrays.sort (array);6intCount=0;7          8 for(inti=0;i<array.length;i++){9if(ARRAY[I]==ARRAY[ARRAY.LENGTH/2]){Tencount++; One             } A         } -if(COUNT&GT;ARRAY.LENGTH/2){ -returnArray[array.length/2]; the}Else{ -return0; -         } -           +     } -}

Method Three: Use HashMap

The HashMap method is straightforward, saves each number and its corresponding number of times, and then traverses the entire hashmap, finding the key that exceeds the length of the array by half

1  Public classSolution {2 Public intMorethanhalfnum_solution (int[] Array) {3hashmap<integer,integer> map =NewHashmap<integer,integer>();4          5 for(inti=0;i<array.length;i++){6              7if(!Map.containskey (Array[i])) {8Map.put (array[i],1);9}Else{TenintCount =Map.get (Array[i]); OneMap.put (array[i],++count); A             } -         } -Iterator iter =Map.entryset (). iterator (); the while(Iter.hasnext ()) { -Map.entry Entry =(Map.entry) Iter.next (); -Integer key =(Integer) Entry.getkey (); -Integer val =(Integer) entry.getvalue (); +if(VAL&GT;ARRAY.LENGTH/2){ -returnkey; +             } A         } atreturn0; -}

It is felt that this approach is mainly about HASHMAP traversal.

Briefly review the HashMap traversal method:

Method 1: Use for each to remove Map.entryset () and get key and value

1  new hashmap<string, string>(); 2   for (entry<string, string> entry:map.entrySet ()) {3      entry.getkey (); 4      entry.getvalue (); 5  }

Method 2: call Map.entryset () of the set iterator and determine if there are elements that can be iterated by the Hasnext () method

1 New Hashmap<string, string>(); 2 iterator<map.entry<string, string>> Iterator = map.entryset (). Iterator (); 3   while (Iterator.hasnext ()) {4      map.entry<string, string> Entry = iterator.next (); 5      Entry.getkey (); 6      Entry.getvalue (); 7  }

Method 3: get the key collection through the keyset () method in HashMap, and retrieve the value by loop

New Hashmap<string, string>();  for (String key:map.keySet ()) {3     map.get (key); 4}

Method 4: save Map.entryset () through temporary variables, traverse output

1 New Hashmap<string, string>(); 2 set<entry<string, string>> entryset = map.entryset (); 3  for (entry<string, string> entry:entryset) {4    entry.getkey (); 5     Entry.getvalue (); 6 }

Reference: Summary of HashMap traversal methods

A number of more than half occurrences in a offer-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.