Leetcode_Majority Element
来源:互联网 发布:淘宝客服如何算提成 编辑:程序博客网 时间:2024/06/14 05:04
Tag
Array/Divide and Conquer/Bit Manipulation
Difficulty
Easy
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.
Code
- Array:
Moore Voting Algorithm
每找出两个不同的element,即成对删除count–,否则count++
时间复杂度O(n)
class Solution: # @param {integer[]} nums # @return {integer} def majorityElement(self, nums): count=0 major_Element=0 for num in nums: if count==0: major_Element=num count=count+1 else: if num==major_Element: count =count+1 else: count = count-1 return major_Element
- Divide and Conquer
将数组划分成两半,分别递归查找这部分的多数元素,如果相同,则为多数元素,否则为其中之一,判断其一即可
时间复杂度O(nlogn)
class Solution(object): def majority(self,nums,left,right): if left == right: return nums[left] mid = (left+right)/2 lm = self.majority(nums,left,mid) rm = self.majority(nums,mid+1,right) if lm == rm: return lm if nums[left:right+1].count(lm) > nums[left:right+1].count(rm): return lm else: return rm def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ return self.majority(nums,0,len(nums)-1)
- Bit Manipulation
统计int的32位上每一位的众数,每一位的众数即组成了Majority Element的每一位。
class Solution {public: int majorityElement(vector<int>& nums) { int major = 0, n = nums.size(); for (int i = 0, mask = 1; i < 32; i++, mask <<= 1) { int bitCounts = 0; for (int j = 0; j < n; j++) { if (nums[j] & mask) bitCounts++; if (bitCounts > n / 2) { major |= mask; break; } } } return major; } };
0 0
- leetcode_Majority Element
- leetcode_Majority Element
- Leetcode_Majority Element
- LeetCode_majority-element
- leetcode_Majority Element
- Leetcode_Majority Element
- leetcode_Majority Element II
- leetCode_Majority Element II【多数投票法】
- leetcode_Majority Element (找出现次数大于一半的元素)-easy
- Element
- Element
- element
- element jquery
- element.childNodes
- dom element
- expat:element
- Element Object
- Element 对象
- SpringMVC源码总结(十一)mvc:interceptors拦截器介绍
- 关于STL中map用法详解
- js基本效果
- 东东的女朋友(二)【贪心】+【区间覆盖】
- OpenWrt源码下载说明
- Leetcode_Majority Element
- openSession 和getCurrentSession的区别
- Hibernate一对多关系详解
- javaScript数组方法
- Mybatis学习【1】
- 体验Ipython 惹得祸
- ORTC以及WebRTC的未来【转】
- 设计模式-观察者模式
- java.lang.IllegalArgumentException: Malformed /uxxxx encoding