Majority Element


@swatisaoji1 That array does not have a majority element, so it is not a valid input for this problem.

@zpng The problem states that only arrays with a majority element will be passed as input. Your array does not have a majority element, so it is not valid input. For the version of the problem that works with arrays that may or may not have a majority element, you need to make a final linear pass over the array, verifying that the
candidate
is indeed a majority element.

class Solution {
public int majorityElement(int[] nums) {
if (nums.length == 0)
return 1;int majorElem = nums[0], count = 1; for (int i=1; i<nums.length; i++) { if (nums[i] == majorElem) { count++; } else { count ; } if (count == 0) { majorElem = nums[i]; count = 1; } } if (count > nums.length/2) return majorElem; count = 0; for (int i=0; i<nums.length; i++) { if (nums[i] == majorElem) { count++; } if (count > nums.length/2) break; } return count > nums.length/2 ? majorElem : 1; }
}