码迷,mamicode.com
首页 > 编程语言 > 详细

229. Majority Element II java solutions

时间:2016-07-05 18:32:14      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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:

  1. How many majority elements could it possibly have?
  2. 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

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5644388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!