229. Majority Element II
来源:互联网 发布:pdf电子书 知乎 编辑:程序博客网 时间:2024/06/07 02:11
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
Hint:
- How many majority elements could it possibly have?
摘自:
https://leetcode.com/discuss/43175/c-solution-with-explanation-o-n-time-and-o-1-space
We can apply the same idea as easy version of majority element. If we remove three elements with different value at the same time, finally we should filter out the majority elements. So in the first pass, we search for possible majority elements (the number of majority element <3), and then for each candidate, we scan the array again to confirm wether it's majority or not.
public static List<Integer> majorityElement(int[] nums){if (nums == null || nums.length == 0)return new ArrayList<Integer>();List<Integer> result = new ArrayList<Integer>();int number1 = nums[0], number2 = nums[0], count1 = 0, count2 = 0, len = nums.length;for (int i = 0; i < len; i++){if (nums[i] == number1)count1++;else if (nums[i] == number2)count2++;else if (count1 == 0){number1 = nums[i];count1 = 1;} else if (count2 == 0){number2 = nums[i];count2 = 1;} else{count1--;count2--;}}count1 = 0;count2 = 0;for (int i = 0; i < len; i++){if (nums[i] == number1)count1++;else if (nums[i] == number2)count2++;}if (count1 > len / 3)result.add(number1);if (count2 > len / 3)result.add(number2);return result;}
0 0
- 229.Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- Leetcode-linked-list-cycle
- Unison(rpm方式)安装及应用--nginx高可用
- putty 回滚问题
- sqlite3_step (21: out of memory) rs的一种错误原因。
- poj1904(二分图最优匹配)
- 229. Majority Element II
- Leetcode-palindrome-number
- android实现自定义相机以及图片的水印
- 学习之maven(1)
- syms使用错误
- Java RMI 简介及其优劣势总结
- react的初始化阶段
- 不是技术牛人,如何拿到国内IT巨头的Offer
- 堆栈程序理解