Majority Element

来源:互联网 发布:不想找女朋友 知乎 编辑:程序博客网 时间:2020/11/24 13:53

题目来自于:

LeetCode 169.Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.


思路:准备一个计数器count,如果循环过程中遇到不同值的两个元素,则count—即删除这两个元素,所以最后剩下的元素就是所要找的元素。

language: javascript

/** * @param {number[]} nums * @return {number} */var majorityElement = function(nums) {    var count = 0;    var number = 0;    for(var i=0;i<nums.length;i++){        if(count === 0){            number = nums[i];            count = 1;        }else{            if(number == nums[i]){                count++;            }else{                count--;            }        }    }    return number;};


0 0
原创粉丝点击