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.
题意找出数组中出现次数大于n/2的数;
package leetcode;
public class MajorityElement {
public int majorityElement(int[] nums) {
int count = 1;
int key = nums[0];
for (int i = 1; i<nums.length; i++){
if (key == nums[i]) count++;
else count--;
if (count == 0){
key = nums[i];
count = 1;
}
}
return key;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums = {1,1,1,1,1,1,1,1,1,1,1,1,2,3123,123,124123,123,12312,3123,123,123,123,123};
System.out.println(new MajorityElement().majorityElement(nums));
}
}