给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
public class Solution { /* * @param nums: a list of integers * @return: find a majority number */ public int majorityNumber(List<Integer> nums) { // write your code here int count = 0; int result = 0; for (int i = 0; i < nums.size(); i++) { if (count == 0) { result = nums.get(i); count++; } else { if (result != nums.get(i)) { count--; } else { count++; } } } return result; } }