[LeetCode] 169. Majority Element

题:https://leetcode.com/problems/majority-element/description/

题目

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

思路

两种:

1

遍历nums,每访问一个元素,查询是否存在字典中,若已经存在,将对应的计数加一;否则,将该元素存入字典中,并设置对应的计数为一。
遍历字典,查找对应计数值最大的元素,返回该元素。

2

设出现最多的元素
由于出现的次数大于n/2,可以看作 从 出现最多的那个元素 和 非该元素 中挑选 出现最多的元素,并且不需要知道其出现的次数。可以通过比较的方式得到。

############# 方法 一 ############

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        countdict = {}
        for i in nums:
            if i in countdict.keys():
                countdict[i] += 1
            else:
                countdict[i] = 1
        maxcount = float('-inf')
        maxkey = -1
        for i in countdict.keys():
            # print(i,countdict[i])
            if maxcount<countdict[i]:
                maxkey = i
                maxcount = countdict[i]
                
        return maxkey

############### 方法 二 ##############

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        major = nums[0]
        count = 1
        
        for i in range(1,len(nums)):
            
            if count==0:
                major = nums[i]
                count = 1
            elif major == nums[i]:
                count += 1
            else:
                count -= 1
                
        return major

第二版

设置 curNum 为当前数, cnt 记录当前数出现的次数。

使用 cnt 来统计一个元素出现的次数,当遍历到的元素和统计元素不相等时,令 cnt–。如果前面查找了 i 个元素,且 cnt == 0,说明前 i 个元素没有 majority,或者有 majority,但是出现的次数少于 i / 2,因为如果多于 i / 2 的话 cnt 就一定不会为 0。此时剩下的 n - i 个元素中,majority 的数目依然多于 (n - i) / 2,因此继续查找就能找出 majority。

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

这种写法条理更清楚。

class Solution {
    public int majorityElement(int[] nums) {
        int cnt = 0;
        int majority  = nums[0];
        for(int num:nums){
            if(cnt == 0)
                majority = num;
            if(majority == num)
                cnt ++;
            else
                cnt --;
        }
        return majority;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值