[Array]Majority Element
生活随笔
收集整理的這篇文章主要介紹了
[Array]Majority Element
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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.
方法:充分利用主元素出現(xiàn)次數(shù)大于? n/2 ? 這個條件,根據(jù)這個條件,順序遍歷整個數(shù)組,我們可以為一個元素設置一個計數(shù)器,假設以第一個元素為例,為第一個元素設置一個count=1,表明出現(xiàn)過一次,然后遍歷第二個元素,當?shù)诙€元素與第一個元素相等時,count++,表明出現(xiàn)過兩次,當?shù)诙€元素與第一個元素不等時,count- -,當遍歷第三個元素時如果發(fā)現(xiàn)count=0,則為第三個元素設置一個計數(shù)器,依次類推。
時間復雜度:O(n)
空間復雜度:O(1)
轉(zhuǎn)載于:https://www.cnblogs.com/GoFly/p/5751064.html
總結(jié)
以上是生活随笔為你收集整理的[Array]Majority Element的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java代理系列-静态代理
- 下一篇: 最小化托盘示例工程