Number of occurrences more than half in an array

Source: Internet
Author: User

Title: There is a number in the array that appears more than half the length of the array, please find this number.



Idea: First see this topic, an array of numbers appear more than half of the length of the array, it means that the number of occurrences more than the number of other numbers in the array number of occurrences of the sum. We can use two values to record when we traverse the array, one is the number of occurrences of the array count, a result that is used to save it, and we save the first number of the array as the result of the arr[0] as the results are compared with the next number, Count is 1, If the next number is the same as the previously saved number, count+1 is count-1 if it is different from the previously saved number. If the number is 0, we need to save its next number and set the number of times to 1. Since the number to be searched is more than half the length of the array, the last number set to 1 is the number we are looking for.

Code:

#include <iostream>using namespace std;int serach (int arr[],int len) {int count=1;int result=arr[0];for (int i=1;i& lt;len;i++) {if (count==0) {result=arr[i];count=1;} else if (result = = Arr[i]) count++;elsecount--;} return result;} int main () {int arr[]={1,2,3,2,2,2,5,4,2};int sz=sizeof (arr)/sizeof (arr[0]); int Ret=serach (ARR,SZ); Cout<<ret <<endl;return 0;}


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.