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) { return helper(nums,0,nums.length-1); } public int helper(int [] nums,int begin,int end){ if(begin==end){ return nums[begin]; }else{ int mid = begin+ (end-begin)/2; int left = helper(nums,begin,mid); int right = helper(nums,mid+1,end); if(left == right){ return left; }else{ int leftcount=0,rightcount=0; for(int i=begin;i<=end;i++){ if(nums[i]==left){ leftcount++; }else if(nums[i]==right){ rightcount++; } } if(leftcount >rightcount){ return left; }else{ return right; } } } } }