Accepted java solution


  • 16
    V

    public class Solution {

    public int majorityElement(int[] num) {
    
        Arrays.sort(num);
    
        return num[num.length/2];
        
    }
    

    }


  • 0
    W

    OMG,I wrote a insert sort and got timeout LOL.


  • 0

    public int majorityElement(int[] nums) {
    if(nums.length==1) return nums[0];
    Arrays.sort(nums);
    int sum = 1;
    for(int i = 0; i <nums.length-1; i++){
    if(nums[i]==nums[i+1]){
    sum++;
    }else{
    sum = 1;
    }
    if(sum>nums.length/2){
    return nums[i];
    }
    }
    return nums[0];//This part must have some problem!
    }


Log in to reply
 

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