`
随便小屋
  • 浏览: 102684 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

Leetcode-169-Majority Element

阅读更多

Majority Element

 

来自 <https://leetcode.com/problems/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.

题目解读:

 

给一个长度为n的数组,找出最主要元素。最主要元素是指改元素在数组中出现的此时多余 n/2 次。假设数组不为空并且数组中一定存在最主要元素。

解析:

 

解法一:对数组中的元素由大到小或由小到大进行排序,返回位置 n/2 的元素就是最主要元素。

 

解法二:

 

Moore's voting algorithm算法

 

算法的基本思想是每次找出一对不同的元素,重数组中删掉,直到数组为空或只有一种元素。不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e

 

在遍历开始之前,记最主要的元素majority为空。其出现的此时count=0

 

然后遍历数组nums时,如果count=0,表示当前没有候选元素,也就是说之前便利过程中没有找到超过半数的元素,那么如果超过半数的元素majority存在,那么剩下的子数组中,出现次数也一定超过半数。因此我们可以将院士问题转化为其它的子问题,此时majority为当前元素,同时count=1.

 

如果当前元素nums[i]==majority,那么count++.(没有找到不同元素,只需要把相同的元素累计起来)

 

如果当前元素nums[i]!=majority,那么count--.(相当于删除一个majority)

 

如果遍历结束后,count不为0,那么元素majority即为要寻找的元素。

 

解法三:

 

Map进行实现,将数组元素作为key,将该元素出现的次数作为key所对应的value值。Map初始化为空,当遇见一个新的数组元素时,先直接将该元素作为key值存放到Map中,其对应的value值为1.下次再遇见该元素,则直接将value值加1即可。数组遍历结束后,取出value大于 n/2 所对应的key值就是要寻找的最主要的元素。

 

解法四:

 

这个方法是看了Solution之后才知道的,这里假设数据值范围为(1,2^32-1),那么我们需要一个32个元素的list,初始值都为0。这里的32表示元素转换成二进制之后的32位数。对于每一位数,遍历数据list里的所有数,记录该位为1的个数。如果个数>=len(num)/2+1,则该位为1,否则为0。同理算出每一位,再转换成10进制数即为出现次数最多的数

来自 <http://www.tuicool.com/articles/EFbAnqa>

 

解法一代码:

  public int majorityElement(int[] nums) {
        if(null == nums)
        	return 0;
        Arrays.sort(nums);
        return nums[nums.length/2];

    }

 解法一性能:



 

 

 

解法二代码:

 

    public int majorityElement(int[] nums) {
        if(nums == null)
			return 0;
		int count = 0;
		int majority=0;

		for(int i=0; i<nums.length; i++) {
			if(0 == count) {
				majority = nums[i];
				count = 1;
			} else if(majority == nums[i]) {
				count++;
			} else {
				count --;
			}
		}
		return majority;
    }

解法二性能:



 

解法三代码:

public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
		for(int a: nums) {
			if (count.containsKey(a)) {
				count.put(a, count.get(a)+1);
			} else {
				count.put(a, 1);
			}
		}
		for(int item : count.keySet()) {
			if(count.get(item) > (nums.length/2)) {
				return item;
			}
		}
		return 0;
    }

解法三性能:



 

 

解法四代码:

解法四代码:
    public int majorityElement(int[] nums) {
        if (nums == null || nums.length == 0)
			return 0;
		int[] dig = new int[32];
		for (int i = 0; i < nums.length; i++) {
			int temp = nums[i];
			for (int j = 0; j < 32; j++) {
				dig[j] += temp & 1;
				temp = temp >> 1;
			}
		}
		int count = nums.length / 2;
		int res = 0;
		int temp = 1;
		for (int i = 0; i < 32; i++) {
			if (dig[i] > count)
				res = res | temp;
			temp = temp << 1;
		}
		return res;
    }

 

解法四性能:



 

 

分享到:
评论

相关推荐

    leetcode和oj-leetcode-swift:我的leetcode解决方案和想法

    169“Majority Element”的解决方案。 注意力! 因为我直接在leetcode Judge web里面写代码,所以很多getSolution()没有测试用例。 如果您想在Xcode中进行测试,请自行添加测试用例! 每个问题的结构如下: struct q...

    戳气球leetcode-leetcode:leetcode

    leetcode category other hot keywords:Palindrome(mic), Subsequence Array 螺旋矩阵Spiral Matrix 顺时针打印矩阵 Next Permutation Product of Array Except Self 189.rotate-array 283.move-zero Range Sum ...

    Leetcode的ac是什么意思-LeetCodeInJava:leetcode-java

    #169 Majority Element #171 Excel Sheet Column Number #217 Contains Duplicate #226 Invert Binary Tree #237 Delete Node in a Linked List #238 Product of Array Except Self #242 Valid Anagram #258 Add ...

    圆和矩形是否重叠leetcode-leetcode_solutions:leetcode_solutions

    圆和椭圆重叠leetcode ——#158 尖端 关心特殊情况 ...是一个常数,所以可以计算出缺失的那个169.Majority Element -&gt; Hashtable | Boyer-Moore 多数投票算法283. 移零 -&gt; 27. 移除元素243.Shortest Word Dista

    leetcode有效期-algorithmTask:算法任务

    leetcode有效期 algorithmTask 数据结构与算法练习 ...英文版:https://leetcode.com/problems/majority-element/ 中文版:https://leetcode-cn.com/problems/majority-element/ Missing Positive(求缺失

    Leetcode Majority Element python 多种思路求集合中出现最多次数的值 提升计算机思维

    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-...

    LeetCode最全代码

    27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C++](./C++/remove-element.cpp) [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation]...

    leetcode答案-exercise-book:算法练习记录

    Element II 解决方法:Majority Voting算法的变种。但是最终的算法实现形式,很难理解。 2018-08-19 19:16 LeetCode: 79. Word Search 解决方法:DFS LeetCode: 31. Next Permutation 解决方法:掌握排列组合的字典...

    leetcode中国-leetcode:刷算法了

    leetcode中国 Leetcode Set Matrix Zeroes 第一种 通过一次遍历记录所有为0的索引(Python中enumerate()输出当前列表的索引) 再遍历一次, 根据记录的索引进行置0 第二种 ...Majority Element 多数投票算法

    leetcode有效期-Datawhale-Coding:Datawhale-编码

    leetcode有效期 Datawhale-Coding ...Element(求众数) 英文版: 中文版: Missing Positive(求缺失的第一个正数)[作为可选] 英文版: 中文版: Linked List Cycle I(环形链表) 英文版: 中文版: Merge k

    leetcode卡-Programming:编程

    leetcode卡 Programming 课程设计:光城 、LeoLRH 组队学习说明:利用自己所熟知的编程语言,具有一定基础,讨论在面试中可能出现的数据结构问题,一起学习重温经典数据结构 ...Element(求众数) Missi

    gasstationleetcode-LeetCode_Practice:我的LeetCode练习从2020年开始

    169_Majority_Element 229_Majority_Element_II 274_H_索引 275_H_Index_II 217_Contain_Duplicate 55_Jump_Game 45_Jump_Game_II 121_Best_Time_to_Buy_and_Sell_Stock 122_Best_Time_to_Buy_and_Sell_Stock_

    javalruleetcode-leetcode:力码解决方案

    leetcode leetcode_java Java版中的解决方案。 Dectinc_Chen 解决问题清单 已解决问题列表 [除Self之外的数组乘积](md/除Self.md之外的数组乘积) - 2015-10-23 [删除链表中的节点](md/删除链表中的节点.md) - 2015-...

    leetcode2sumc-DataWhale_exercise:用C++编程

    leetcode 2 sum c DataWhale_exercise programming in ...Element(求众数) 英文版: 中文版: Missing Positive(求缺失的第一个正数)[作为可选] 英文版: 中文版: Linked List Cycle I(环形链

    LeetCode:LeetCode问题

    [C ++](./ Algorithms / Majority Element II / Source.cpp) 中等的 2015年7月4日 228 [C ++](./算法/摘要范围/Source.cpp) 简单的 2015年7月1日 227 [C ++](./ Algorithms / Basic Calculator II / Sour

    validnumberleetcode自动机----:数据结构打卡

    valid number leetcode 自动机 ...Element(求众数) 英文版: 中文版: Missing Positive(求缺失的第一个正数)[作为可选] 英文版: 中文版: Linked List Cycle I(环形链表) 英文版: 中文版: Me

    LeetCode判断字符串是否循环-lc:液晶显示器

    majority element ii . 使用 "摩尔投票法"。 LCA 二叉树最近共同祖先问题. 递归结题的思路,在左子树、右子树查找两个节点,可能的结果有: 该节点就是其中的一个节点,则返回该节点 两个节点都不在左边,那么肯定都...

    leetcode添加元素使和等于-njuee_LeetCode_Solutions:本仓库主要记录平时遇到的一些编程问题、算法、思路

    leetcode添加元素使和等于 本项目为Njueers所共享 仓库内容主要为平时刷题的submit、遇到的一些经典题解、coding时所作的笔记等 Basic Knowledge文件夹下为一些基础但相对重要的C++知识点/笔记 Cpp文件夹下主要为...

    validnumberleetcode自动机-code_with_py:编程任务

    valid number leetcode ...Element(求众数) 英文版: 中文版: Missing Positive(求缺失的第一个正数)[作为可选] 英文版: 中文版: Linked List Cycle I(环形链表) 英文版: 中文版: Merge k

    cpp-算法精粹

    Majority Element Rotate Array Contains Duplicate Contains Duplicate II Contains Duplicate III Product of Array Except Self Game of Life Increasing Triplet Subsequence 单链表 Reverse Linked List Odd ...

Global site tag (gtag.js) - Google Analytics