o(n) solution in Java


  • -1
    Z

    public class Solution {

    public int majorityElement(int[] nums) {
        
        Arrays.sort(nums);
        
        int size=nums.length;
        
        int count=1;
        
        for(int i=0;i<size-1;i++){
           
            if(nums[i]==nums[i+1]){
                count++;
            }else{
                count=1;
            }
             if(count>size/2)return nums[i];
            
        }
        return nums[0];
        
    }
    

    }


  • 2
    S

    Wouldn't sorting the array mean that the solution is already nlogn?


Log in to reply
 

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