Java without sort or hashmap


  • 15
    T
    public class Solution {
        public int majorityElement(int[] nums) {
            if (nums == null || nums.length ==0){
                return 0;
            }
            int count = 1;
            int major = nums[0];
            for (int i = 1; i < nums.length; i++){
                if (nums[i] != major){
                    count--;
                } else {
                    count++;
                }
                if (count == 0){
                    major = nums[i];
                    count = 1;
                }
            }
            return major;
        }
    

    }


  • 0
    R

    Your method is quite more efficient than mine. I used hashmap and it cost too much time.


  • 0
    L

    How do you handle the case when no majority element is found?


  • 0
    P

    This is not a possibility(as mentioned in the question)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.