[Sword refers to offer] more than half of the number appearing in the array

Source: Internet
Author: User
/* Thinking:
There is an array in the number more than half the length of the array, that is, it appears more times than all other numbers appear and more.
so we can consider saving two values while traversing an array: One is a number in the array and one is the number of times.
when we traverse to the next number, if the next number is the same as the number we saved before, the number is 1
if the next number and the previously saved number are not used, the number is reduced by 1.
If the number is 0, we need to save the next number and set the number to 1.
Since the number we are looking for appears to be more than the sum of the number of other numbers, the number to be found is definitely the last one to set the number to 1 o'clock the corresponding number/
class Solution {public
:
    int Morethanhalfnum_solution (vector<int> numbers) {
    	int len=numbers.size ();
		int result=numbers[0], time=1;//result answer, time saved number of occurrences for
		(int i=1; i<len; i++)
		{
			if (time==0)
			{
				result=numbers[i];
				time=1;
			}
			else if (Result==numbers[i])
				time++;
			else
				time--;
		}
		int check=0;
		for (int i=0; i<len; i++)//check for more than half of the number
			if (result==numbers[i)
				check++;
		if (Check*2<=len) return 0;
		return result;
    }
;

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.