Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than n/2 times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:

Special thanks to @ts for adding this problem and creating all test cases.

代码:

class Solution {
public:
    int majorityElement(vector<int> &num) {
		int total = num.size();
		int match;
		int times = 0;
		for (int i=0; i<total; i++) {
			if (0 == times) {
				match = num[i];
				times = 1;
			} else {
				if (match == num[i]) {
					++times;
				} else {
					--times;
				}
			}
			if (times > total / 2) {
				break;
			}
		}

		return match;
    }
};


你可能感兴趣的:(Majority Element)