Leetcode 229 JavaScript

pimkle發表於2019-03-28
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var majorityElement = function(nums) {
    nums.sort();
    // console.log(nums)
    let len = nums.length;
    if(!len){
        return []
    }
    let pointer = -1;
    let counter = 0;
    是let last = nums[0];
    let res = []
    while(++pointer < len){
        if(nums[pointer] === last){
            counter++
        } else {
            if(counter > len / 3){
                res.push(last)
            }
            counter = 1
            last = nums[pointer]
        }
    }
    if(counter > len / 3){
        res.push(last)
    }
    return res
};
複製程式碼

相關文章