229. Majority Element II java solutions
Posted Miller1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了229. Majority Element II java solutions相关的知识,希望对你有一定的参考价值。
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?
- Do you have a better hint? Suggest it!
Subscribe to see which companies asked this question
1 public class Solution { 2 public List<Integer> majorityElement(int[] nums) { 3 List<Integer> ans = new ArrayList<Integer>(); 4 if(nums.length <= 0) return ans; 5 Arrays.sort(nums); 6 int i = 0,len = nums.length,tmp = 0; 7 while(i < len - len/3){ 8 if(nums[i] == nums[i+len/3]){ 9 tmp = nums[i]; 10 ans.add(tmp); 11 i += len/3; 12 while(i < len - len/3 && nums[i] == tmp)i++; 13 }else i++; 14 } 15 return ans; 16 } 17 }
解法二:
可用一个hashmap 来计算元素出现个数,但是超过space O(1) 的限制。
解法三:
https://discuss.leetcode.com/topic/32510/java-easy-version-to-understand/2 二刷在研究。
以上是关于229. Majority Element II java solutions的主要内容,如果未能解决你的问题,请参考以下文章
229 Majority Element II 求众数 II