My JavaScript solution


  • 0
    M

    First,I find the most frequently occurring element and record this element and its number of occurrences. Then I compare the times with n/2.

    /**
     * @param {number[]} nums
     * @return {number}
     */
    var majorityElement = function(nums) {
        let max = 0, res
        for (let i = 0; i < nums.length; i++) {
            let count = 0
            if (nums[i] != 'a') {
                let temp = nums[i]
                for (let j = i; j < nums.length; j++) {
                    if (nums[j] === temp) {
                        count ++
                        nums[j] = 'a'
                    }
                }
                
                if (count > max) {
                    max = count
                    res = temp
                } 
            }
        }
        let halfLen = Math.floor(nums.length / 2)
        if (max >= halfLen) {
            return res
        } 
        return null
    };
    

Log in to reply
 

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