SoFunction
Updated on 2025-03-08

Detailed explanation of the algorithm of most elements of front-end JavaScript

Topic: Most elements

Given an array of size nums , return most of the elements in it. Most elements refer to elements that appear in an array with a number of times greater than ⌊ n/2 ⌋.

You can assume that the array is non-empty and that the given array always has a majority of elements.

Example 1:

Input: nums = [3,2,3]
Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]
Output: 2

hint:

n ==

1 <= n <= 5 * 104

-109 <= nums[i] <= 109

untie:

Method 1: Map implementation

By passing the map, all occurrence elements and the number of occurrences are stored. Because of the uniqueness of the map, it is then traversed to find the maximum value. The first map operation time complexity is o(1), the second time and o(n), so the overall sum is O(n); but since a map space is opened, the space complexity is also o(n)

/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    let map = new Map()
    for(let i=0;i<;i++){
        if((nums[i])){
            (nums[i],(nums[i])+1)
        }else{
           (nums[i],1)
        }
    }

    for(let [key,val] of ()){
        if(val>/2){
            return key
        }
    }
};

Method 2: Sort

Idea: sort the array. If a number appears at a frequency greater than n/2, then this number is the position of the array /2.

Complexity analysis: Time complexity: O(nlogn), the time complexity of fast-rowing. Space complexity: O(logn), the space complexity that requires logn to be sorted

var majorityElement = function (nums) {
    ((a, b) => a - b);
    return nums[( / 2)];
};

The above is the detailed explanation of the algorithm for most elements of front-end JavaScript. For more information about most elements of JavaScript, please pay attention to my other related articles!