169. Majority Element
2016-08-23 16:27
162 查看
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.
思路:
因为一定存在Majority Element,所以Majority Element的个数减去其他所有数字的个数一定大于0
public int majorityElement(int[] nums) {
int count = 0;
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (count == 0) {
count = 1;
res = nums[i];
} else {
if (res == nums[i]) {
count++;
} else {
count--;
}
}
}
return res;
}
more than
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
思路:
因为一定存在Majority Element,所以Majority Element的个数减去其他所有数字的个数一定大于0
public int majorityElement(int[] nums) {
int count = 0;
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (count == 0) {
count = 1;
res = nums[i];
} else {
if (res == nums[i]) {
count++;
} else {
count--;
}
}
}
return res;
}
相关文章推荐
- 2018.03.07 leetcode 打卡 #169. Majority Element
- 169 Majority Element
- Leetcode 169. Majority Element
- 169. Majority Element 破解思路
- LeetCode 169 -Majority Element ( JAVA )
- LeetCode OJ 169. Majority Element
- [Leetcode]169. Majority Element
- Leetcode 169. Majority Element (Easy) (cpp)
- LeetCode OJ-169. Majority Element
- Leetcode 169 Majority Element
- 169. Majority Element
- 169. Majority Element
- 169. Majority Element
- 【Leetcode】169. Majority Element
- 169. Majority Element--寻找数组中出现次数超过一半的数据,229. Majority Element II--注意最后的检测
- [LeetCode]169. Majority Element
- 169. Majority Element
- 169. Majority Element
- LeetCode 169 Majority Element
- LeetCode 169. Majority Element