Home  >  Article  >  Web Front-end  >  How to find the mode in javascript

How to find the mode in javascript

藏色散人
藏色散人Original
2022-01-19 15:12:042408browse

How to find the mode in javascript: 1. Create a new array; 2. Count the number of occurrences of each value; 3. Traverse the array and find the mode.

How to find the mode in javascript

The operating environment of this article: Windows 7 system, javascript version 1.8.5, DELL G3 computer

How to find the mode in javascript?

LeetCode's finding the mode - JavaScript implementation

Getting the mode

Given an array of size n, find the mode. The mode refers to the elements that appear more than ⌊ n/2 ⌋ in the array.

You can assume that the array is non-empty and that there is always a mode for a given array.

Example 1:

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

Example 2:

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

##My thoughts:New An array, count the number of occurrences of each value, and then traverse the array to find the mode.

const majorityElement = function (nums) {
    let arry = []
    for (let i in nums) {
        if (!arry[nums[i]]) {
            arry[nums[i]] = !!arry[nums[i]] + 1
        }else {
            arry[nums[i]] ++
        }
    }
    for(let i in arry){
        if(arry[i] > nums.length/2){
            return i
        }
    }
};

The fastest solution to leetcode:

Solution ideas:Use a counter and an intermediate value, first let the intermediate value equal For the first bit of the array, during a traversal, if the counter is the same, the counter will be incremented by one, and if it is different, the counter will be decremented. When it reaches 0, it will be replaced by the value currently traversed. After the traversal is completed, the intermediate value will be returned, which is mode. [Recommended study: "
js Basic Tutorial"]

It feels very strange, there is an idea of ​​offset in it

var majorityElement = function(nums) {
    let count = 0;
    let majority = nums[0];
    
    for (let i = 0; i < nums.length; i++) {
        if (count === 0) {
            majority = nums[i];
        }
        
        if (majority === nums[i]) {
            count++;
        } else {
            count--;
        }
    }
    return majority;
};

The above is the detailed content of How to find the mode in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn