Major Element

Posted amazingzoe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Major 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.

Example 1:

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

Example 2:

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


class Solution {
    public int majorityElement(int[] nums) {
        int result = 0, count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (count == 0) {
                result = nums[i];
            }
            
            if (nums[i] == result) {
                count++;
            } else {
                count--;  
            }
        }
        
        return result;
    }
}

 

以上是关于Major Element的主要内容,如果未能解决你的问题,请参考以下文章

Baozi Leetcode solution 229: Major Element II

Selenium Xpath元素无法定位 NoSuchElementException: Message: no such element: Unable to locate element(代码片段

169. Majority Element

leetcode 169. Majority Element

js代码片段: utils/lcoalStorage/cookie

TP5报如下的错误 Indirect modification of overloaded element of thinkpaginatorCollection has no effect(代码片段