LeetCode 169. Majority Element (数组的主要元素、摩尔投票算法)
2017-05-24 19:25
676 查看
4000
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
输入一个数组,找到其中的主要元素(主要元素的个数大于n/2向下取整)。
思路①将数组排序后,位于n/2向下取整位置的即为主要元素。
思路②Moore's voting algorithm: 不断删去数组中两个不同的数,直到最后剩下的数都相同,即为主要元素。
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/2向下取整)。
思路①将数组排序后,位于n/2向下取整位置的即为主要元素。
int majorityElement(vector<int>& nums) { sort(nums.begin(),nums.end()); return nums[nums.size()/2]; }
思路②Moore's voting algorithm: 不断删去数组中两个不同的数,直到最后剩下的数都相同,即为主要元素。
public int majorityElement(int[] num) { int major=num[0], count = 1; for(int i=1; i<num.length;i++){ if(count==0){ count++; major=num[i]; }else if(major==num[i]){ count++; }else count--; } return major; }
相关文章推荐
- LeetCode-169:Majority Element (数组中的多数元素)
- Leetcode:169. Majority Element(找到数组中出现次数最多的元素)
- leetcode 169. Majority Element 多数投票算法(Boyer-Moore Majority Vote algorithm)
- 【LeetCode】169. Majority Element (多数投票算法 & 算法迁移能力)
- leetcode 169. Majority Element | 摩尔投票法
- leetCode 169. Majority Element 数组
- [LeetCode]169. Majority Element(多数元素)
- 字符串算法——查找数组多数元素(Majority Element II)
- ※ Leetcode - Array - 169. Majority Element(快速找出数组中出现过一半以上次数的数,3种写法)
- 算法系列(13) Leetcode 169 Majority Element
- [LeetCode] 169. Majority Element 多数元素
- [LeetCode169]Majority Element求一个数组中出现次数大于n/2的数
- leetcode169---Majority Element(数组中出现次数超过一半的数)
- [LeetCode] Majority Element 最主要的元素
- LeetCode 题解 169. Majority Element(查找多数元素)
- [LeetCode]169. Majority Element寻找数组中超过一半的那个数
- 每天一道LeetCode-----摩尔投票法寻找给定数组中出现个数大于n/2或n/3的元素
- LeetCode:Majority Element I II 投票算法
- leetcode 169. Majority Element 摩尔投票法
- 169. Majority Element | 数组中的主元素