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.

 

需要注意的是:這道題只是要找出多數元素,已經默認存在多數元素了,而不需要去判斷是否存在多數元素。之前的思路就一直卡在怎么判斷多數元素存的的問題上了。

思路解析:

1. 初始化majorityIndex,並且維護其對應count;

2. 遍歷數組,如果下一個元素和當前候選元素相同,count加1,否則count減1;

3. 如果count為0時,則更改候選元素,並且重置count為1;

4. 返回A[majorityIndex] 

原理:如果majority元素存在(majority元素個數大於n/2,個數超過數組長度一半),那么無論它的各個元素位置是如何分布的,其count經過抵消和增加后,最后一定是大於等於1的。 如果不能保證majority存在,需要檢驗。 復雜度:O(N)

 Attention: 循環時從i = 1開始,從下一個元素開始,因為count已經置1

C++版:

class Solution {
  public:
      int majorityElement(vector<int> &num) {
  
          int elem = 0;
          int count = 0;
          
          for(int i = 0; i < num.size(); i++)  {
              
             if(count == 0)  {
                 elem = num[i];
                 count = 1;
             }
             else    {
                 if(elem == num[i])
                     count++;
                 else
                     count--;
             }
             
         }
         return elem;
     }
  };

Python版:

class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def majorityElement(self, nums):
        lenth=len(nums)
        index=0
        count=1
        for i in range(lenth):
            if nums[index]==nums[i]:
                count+=1
            else:
                count-=1
            if count==0:
                index=i
                count+=1
        return nums[index]
                

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM