【LeetCode】 169. Majority Element
2016-12-21 12:42
441 查看
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.
public class Solution {
public int majorityElement(int[] nums) {
int major = nums[0], count = 1;
for (int i = 1; i < nums.length; i++) {
if (count == 0){
count++;
major = nums[i];
} else if (nums[i] == major) {
count++;
} else {
count--;
}
}
return major;
}
}
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
public class Solution {
public int majorityElement(int[] nums) {
int major = nums[0], count = 1;
for (int i = 1; i < nums.length; i++) {
if (count == 0){
count++;
major = nums[i];
} else if (nums[i] == major) {
count++;
} else {
count--;
}
}
return major;
}
}
相关文章推荐
- LeetCode 169:Majority Element
- LeetCode 169. Majority Element
- Leetcode#169. Majority Element(四种解法)
- Majority Element [LeetCode 169]
- LeetCode-169:Majority Element (数组中的多数元素)
- leetcode 169- Majority Element
- leetcode No169. Majority Element
- 【Leetcode】:169. Majority Element 问题 in Go语言
- LeetCode169. Majority Element
- LeetCode- 169. Majority Element - 思路详解 -C++
- [LeetCode]169. Majority Element(多数元素)
- ※ Leetcode - Array - 169. Majority Element(快速找出数组中出现过一半以上次数的数,3种写法)
- [leetcode] 169. Majority Element
- LeetCode169 Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- [LeetCode 169]Majority Element: Moore Voting Algorithm
- Leetcode ☞ 169. Majority Element
- LeetCode169. Majority Element
- (LeetCode 169) Majority Element
- LeetCode笔记:169. Majority Element