【LeetCode-數組】查找大多數元素

題目來源於 LeetCode 上第 169 號(Majority Element)問題,題目難度爲 Easy,AC率52.6%面試

題目地址:https://leetcode.com/problems/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.數組

給定一個數組,數組的長度爲n,找出數組中出現次數超過一半的元素bash

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

你能夠假設數組不爲空,且元素必定存在數組中post

Example 1:
    Input: [3,2,3]
    Output: 3
    
Example 2:
    Input: [2,2,1,1,1,2,2]
    Output: 2
複製代碼

題目解析

採用的是摩爾投票算法,關於什麼是摩爾投票算法,能夠參考知乎這篇文章,戳這裏ui

  1. 定義兩個變量major和count,major 表示出現次數最多的元素,count表示暫時沒法刪除的元素個數
  2. 假設數組第一個數爲出現次數最多的元素,major = nums[0],count=1
  3. 若是後面的數字相等 count+1,不相等 count-1
  4. 若是count爲0,修改major爲當前數,並重置 count=1

算法效率以下: spa

代碼實現

class Solution {
    public int majorityElement(int[] nums) {
        int major = nums[0];
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                count = 1;
                major = nums[i];
            } else if (major == nums[i]) {
                count++;
            } else {
                count--;
            }
        }
        return major;
    }
}
複製代碼

相關文章

【LeetCode-棧】有效的括號3d

【LeetCode-鏈表】面試題-反轉鏈表code

【LeetCode-二叉樹】二叉樹前序遍歷

【LeetCode-數組】數組式整數加法

相關文章
相關標籤/搜索