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 二刷在研究。