【LeetCode 169】Majority Element
生活随笔
收集整理的這篇文章主要介紹了
【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.
?
思路:
找到一個數組中出現次數超過一半的數。排序、哈希等方法就不提了,考慮O(n)的復雜度,有一種傳說中的摩爾投票算法可用。其實也很簡單,初始選第一個元素,依次比對它和其它的元素,若相等則其票數加一,反之則減一,當其票數為0時,更換投票對象為當前的元素,繼續執行,最終即可得結果(前提的數組中存在這樣的數,否則結果不確定是什么,依賴于元素的擺放順序)。
C++:
1 class Solution { 2 public: 3 int majorityElement(vector<int> &num) { 4 5 int len = num.size(); 6 if(len == 0) 7 return 0; 8 9 int cnt = 0, ret = num[0]; 10 for(int i = 0; i < len; i++) 11 { 12 if(cnt == 0) 13 { 14 ret = num[i]; 15 cnt++; 16 } 17 else 18 { 19 if(num[i] == ret) 20 cnt++; 21 else 22 cnt--; 23 } 24 } 25 return ret; 26 } 27 };?
Python:
1 class Solution: 2 # @param {integer[]} nums 3 # @return {integer} 4 def majorityElement(self, nums): 5 ret, cnt = 0, 0 6 7 for val in nums: 8 if cnt == 0: 9 ret = val 10 cnt = 1 11 else: 12 if ret == val: 13 cnt = cnt + 1 14 else: 15 cnt = cnt - 1 16 return ret 17?
轉載于:https://www.cnblogs.com/tjuloading/p/4614397.html
總結
以上是生活随笔為你收集整理的【LeetCode 169】Majority Element的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (三)PHP网页架站
- 下一篇: Fast digital I/O for