leetcode--169. Majority Element
2017-03-13 00:16
417 查看
Question:
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.
Credits: Special thanks to @ts for adding this problem and creating all
test cases.
思路: 1. 有题目可以知道,所求的元素的数目大于⌊ n/2 ⌋,也就意味着,且该元素是存在的。
2. 通过每寻找到两个不同的元素的时候,就一块删除掉,剩下最后的就是所求的元素。(因为该元素数目大于⌊ n/2 ⌋该,也就是一半,所以一次
删除两个不同元素最后就是目标元素)
具体代码实现如下: class Solution {
public:
int majorityElement(vector<int>& nums) {
int majority = 0;
int count = 0;
for(int i = 0; i < nums.size(); i++){
if(count == 0){
majority = nums[i];
count = 1;
}
else{
if(nums[i] == majority)
count ++;
else
count --;
}
}
return majority;
}
};
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.
Credits: Special thanks to @ts for adding this problem and creating all
test cases.
思路: 1. 有题目可以知道,所求的元素的数目大于⌊ n/2 ⌋,也就意味着,且该元素是存在的。
2. 通过每寻找到两个不同的元素的时候,就一块删除掉,剩下最后的就是所求的元素。(因为该元素数目大于⌊ n/2 ⌋该,也就是一半,所以一次
删除两个不同元素最后就是目标元素)
具体代码实现如下: class Solution {
public:
int majorityElement(vector<int>& nums) {
int majority = 0;
int count = 0;
for(int i = 0; i < nums.size(); i++){
if(count == 0){
majority = nums[i];
count = 1;
}
else{
if(nums[i] == majority)
count ++;
else
count --;
}
}
return majority;
}
};
相关文章推荐
- LeetCode 169. Majority Element
- Leetcode 169, 229 Majority element
- [leetcode] 169. Majority Element
- LeetCode 169. Majority Element
- 第二周:[LeetCode]169. Majority Element
- Leetcode 169 Majority Element 分治
- leetcode[169] Majority Element
- 【LEETCODE】169-Majority Element
- 【LeetCode】169. Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- 【LeetCode】169. Majority Element
- Leetcode Everyday: 169. Majority Element
- leetcode记录 169. Majority Element
- [Leetcode]#169 Majority Element
- LeetCode169 Majority Element
- Leetcode 169. Majority Element
- Leetcode:169. Majority Element(JAVA)
- LeetCode - 169. Majority Element
- LeetCode - 169/229 - Majority Element
- 【leetcode】169. Majority Element