Number of occurrences more than half in an array

Source: Internet
Author: User

thought : This topic generally requires O (n) time complexity and O (1) space, in order not to let you use HashMap to calculate the statistics. Here we can implement the idea of 22 elimination, such as an array of arr: 1 2 2 3 2 1 2, then we take the first element Arr[0] as the starting element K, its occurrence count value is 1, and then from the second element arr[1] begin to iterate over the array, if ARR[1] = = k, then we will put count++, if not equal, we will count--, if count is reduced to 0, then re-assign the current element Arr[i] to K,count re-assigned to the value of 1, and then continue this comparison. For this array, the last K must be 2, because 2 appears more than half the times.

 Public Static voidSearchint[] arr) {        if(Arr.length = = 0)return; intCount = 1;//number of times the save occurred        intK = arr[0];  for(inti = 1; i < arr.length; i++) {            if(k = = Arr[i]) count++; Else{Count--; if(count = = 0) {k=Arr[i]; Count= 1; } }} count= 0; //there may be no element more than half, so you need to judge again         for(inti = 0; i < arr.length; i++) {            if(Arr[i] = = k) count++; }        if(Count > Arr.length/2) System.out.println (k); ElseSystem.out.println ("Not Found! "); }

Number of occurrences more than half in an 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.