[leedcode 169] 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.
public class Solution { public int majorityElement(int[] nums) { //如果出现次数大于1/2,最终count的值为正对应的res就是所求 if(nums==null||nums.length<=0) return 0; int res=nums[0]; int count=1; for(int i=1;i<nums.length;i++){ if(count==0){ res=nums[i]; count=1; }else if(nums[i]==res){ count++; }else count--; } return res; } }