"Sword means offer" 19, number of occurrences in the array more than half

Source: Internet
Author: User

The title describes 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.Analysis: To find more than half of the number of occurrences of the array, we can use the two methods, one is using the fast row, the array is sorted, and then directly output the number of the middle position of the sorted array. The second is to use Hashmap<integer,integer>,key is the number in the array, value is the number of times it appears in the array, sequentially scans the array, records the number of occurrences of the array, and outputs a key value that is greater than half the value of the array length. The first method code is simple, here is not table, the second method code is as follows:
1 import java.util.ArrayList;2 import java.util.Arrays;3 import java.util.Collection;4 import Java.util.HashMap;5 import Java.util.Set;6  7  Public classSolution {8     Public intMorethanhalfnum_solution (int[] Array) {9         if(array==NULL|| array.length==0){Ten             return 0 ; One         } A         if(array.length==1){ -             returnarray[0] ; -         } the         intmost=0 ; -hashmap<integer,integer> m =NewHashmap<integer,integer>() ; -         for(inti =0; i < Array.Length; i++){ -            if(!M.containskey (Array[i])) { +M.put (Array[i],1) ; -            } +            Else{ A                inttemp = M.Get(Array[i]); atM.put (Array[i], temp+1) ; -            } -                  -        } -Set<integer> A =M.keyset (); -         for(inttemp:a) { in            if(M.Get(temp) > (array.length/2)){ -most =temp; to            } +        } -         returnMost ; the     } *}

"Sword means offer" 19, number of occurrences in the array more than half

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.