码迷,mamicode.com
首页 > 其他好文 > 详细

主元素

时间:2016-06-22 01:39:38      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

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

 

1、抵消法---- 时间复杂度为O(n),空间复杂度为O(1)

  一旦发现数组中存在两个不同的数,就都删除,直到剩下的数都一样。

  此时剩下的数就是主元素。因为每次抵消操作之后,剩下来的数种,主元素一定也还是超过一半的。

public int majorityNumber(ArrayList<Integer> nums) {
    int count = 0;
    int cur = nums.get(0);
    for(int i=0; i<nums.size(); i++){
        if(count == 0){   // 重新记录
            cur = nums.get(i);
            count = 1;
        }else{  //潜在主元素
            if(cur == nums.get(i)){
                count++;
            }else{
                count--;
            }
        }
    }
    return cur;
}

 

2、用HashMap,时间、空间复杂度都是O(n)

public int majorityNumber_Map(ArrayList<Integer> nums){
    Map<Integer, Integer> map = new HashMap<>();
    for(int i=0; i<nums.size(); i++){
        int num = nums.get(i);
        if(map.containsKey(num)){
            map.put(num, map.get(num)+1);
        }else {
            map.put(num, 1);
        }
        if(map.get(num)>nums.size()/2){
            return num;
        }
    }
    return 0;
}

 

主元素

标签:

原文地址:http://www.cnblogs.com/hesier/p/5605481.html

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