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.
1 public class Solution { 2 /** 3 * @param nums: a list of integers 4 * @return: find a majority number 5 */ 6 public int majorityNumber(ArrayList<Integer> nums) { 7 int count = 0, candidate = -1; 8 for (int i = 0; i < nums.size(); i++) { 9 if (count == 0) { 10 candidate = nums.get(i); 11 count = 1; 12 } else if (candidate == nums.get(i)) { 13 count++; 14 } else { 15 count--; 16 } 17 } 18 return candidate; 19 } 20 }
时间: 2024-12-28 06:03:13