LeetCode(算法)- 169. 多数元素

Posted 放羊的牧码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(算法)- 169. 多数元素相关的知识,希望对你有一定的参考价值。

题目链接:点击打开链接

题目大意:

解题思路

相关企业

  • 亚马逊
  • 谷歌(Google)
  • 微软(Microsoft)
  • 苹果(Apple)
  • Facebook
  • 字节跳动

AC 代码

  • Java
// 解决方案(1)
class Solution 
    public int majorityElement(int[] nums) 
		Map<Integer, Integer> map = new HashMap<>();
		for (int num : nums) 
			map.put(num, map.getOrDefault(num, 0) + 1);
			if (map.get(num) > nums.length / 2) 
				return num;
			
		
		return -1;
	

 
// 解决方案(2)
class Solution 
    public int majorityElement(int[] nums) 
        int x = 0, votes = 0, count = 0;
        for(int num : nums)
            if(votes == 0) x = num;
            votes += num == x ? 1 : -1;
        
        // 验证 x 是否为众数
        for(int num : nums)
            if(num == x) count++;
        return count > nums.length / 2 ? x : 0; // 当无众数时返回 0
    
  • C++
class Solution 
public:
    int majorityElement(vector<int>& nums) 
        int x = 0, votes = 0, count = 0;
        for(int num : nums)
            if(votes == 0) x = num;
            votes += num == x ? 1 : -1;
        
        // 验证 x 是否为众数
        for(int num : nums)
            if(num == x) count++;
        return count > nums.size() / 2 ? x : 0; // 当无众数时返回 0
    
;

以上是关于LeetCode(算法)- 169. 多数元素的主要内容,如果未能解决你的问题,请参考以下文章

leetcode算法169.多数元素

[E摩尔投票] lc169. 多数元素(多数投票算法+经典)

Leetcode刷题100天—169. 多数元素(数组)—day73

Leetcode刷题100天—169. 多数元素(数组)—day73

Leetcode刷题100天—169. 多数元素(数组)—day73

LeetCode刷题169-简单-多数元素