主元素

主元素

给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。

样例

给出数组[1,1,1,1,2,2,2],返回 1

挑战

要求时间复杂度为O(n),空间复杂度为O(1)

 

这题普通的方法还是容易想到的,关键是时间复杂度为O(n),空间复杂度为O(1)。嗯。。数据结构上看到的。

 1 public class Solution {
 2     /**
 3      * @param nums: a list of integers
 4      * @return: find a  majority number
 5      */
 6     public int majorityNumber(ArrayList<Integer> nums) {
 7         int max = nums.get(0);
 8         int x = 1;
 9         for(int i = 1;i<nums.size();i++) {
10             if(nums.get(i) != max){
11                 x--;
12                 if(x <= 0) {
13                     max = nums.get(i);
14                     x = 1;
15                 }
16             }else {
17                 x++;
18             }
19         }
20         return max;
21     }
22 }
View Code

 

posted @ 2015-12-04 15:27  -.-|  阅读(231)  评论(0编辑  收藏  举报