[LeetCode 229] Majority element II
2015-09-02 06:45
323 查看
Given an integer array of size n, find all elements that appear more than
Solution:
At most has two elements in the result, can use two counter to record occurrence. Then calculate if match the condition.
⌊ n/3 ⌋times. The algorithm should run in linear time and in O(1) space.
Solution:
At most has two elements in the result, can use two counter to record occurrence. Then calculate if match the condition.
public List<Integer> majorityElement(int[] nums) { List<Integer> result = new ArrayList<>(); if(nums.length==0) return result; int n1 = nums[0]; int n2 = 0; int count1 = 1; int count2 = 0; for(int i=1;i<nums.length;i++){ if(nums[i] == n1){ count1++; }else if(nums[i] == n2){ count2++; }else{ if(count1 == 0){ n1 = nums[i]; count1++; }else if(count2 == 0){ n2 = nums[i]; count2++; }else{ count1--; count2--; } } } count1 = 0; count2 = 0; for(int i=0;i<nums.length;i++){ if(nums[i] == n1) count1++; if(nums[i] == n2) count2++; } if(count1>nums.length/3) result.add(n1); if(n1 == n2) return result; if(count2>nums.length/3) result.add(n2); return result; }
相关文章推荐
- [Leetcode]#24 Swap Nodes in Pairs
- [Leetcode]#21 Marge Two Sorted Lists
- 公司注册流程
- [Leetcode] #20 Valid Parentheses
- ios开发中,关闭由于SEL引起的警告
- [Leetcode]#19 Remove Nth Node From End of List
- [Leetcode]#17 Letter Combinations of a Phone Number
- mantis修改用户默认密码
- [Leetcode]#14 Longest Common Prefix
- [Leetcode]#9 Palindrome Number
- [Leetcode]#8 String to Integer (atoi)
- [Leetcode]#7 Reverse Integer
- [Leetcode]#6 ZigZag Conversion
- 程序员必须知道的7大基础实用算法及其讲解
- [Leetcode]#2 Add Two Numbers
- LaTeX Footnotes numbered “per page”
- Win 10装机量占据全球台式机总量的5%
- javascript基础1
- 前端工程师技能之photoshop巧用(从效果图到雪碧图)1——准备篇
- erasure coding