lintcode 主元素(Majority Number)(Java)

17 篇文章 0 订阅

题目

给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
You may assume that the array is non-empty and the majority number always exist in the array.

样例

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

分析

思路一:自己的思路
首先我想到的是遍历数组进行计数,那个出现的次数多于一半,它就是我们要找的数,这里采用的是HashMap进行统计。时间复杂度O(n), 空间复杂的O(n)

思路二:查资料所得
查资料看到别人得的的题目要求时间复杂度O(n), 空间复杂的O(1);其实我思路一的解法不符合空间复杂度,看到别人的思路很奇妙。我们可以把这些数看做两种类型,一种主元素,一种非主元素;如果每次我们都从这两种类型中各拿走一个数,直到其中一种类型的数拿光,则最后,剩下的一种类型必定会是主元素类型。

思路三
可以对数组进行排序,因为主元素出现次数大于一半,所以中间那位数必定是主元素,但是排序的话时间复杂度最优为O(nlogn)。

代码

//思路一代码
public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    public int majorityNumber(ArrayList<Integer> nums) {
       HashMap<Integer , Integer> map = new HashMap<Integer , Integer>();

        for (int i = 0; i < nums.size(); i++){

            Integer key = nums.get(i);
            if (map.containsKey(key)){
                map.put(key,map.get(key) + 1);
            }else {
                map.put(key,1);
            }

            if (map.get(key) > nums.size()/2){
                return key;
            }   
        }
        return 0;
    }
}
//思路二
 public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    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;
    }
}

题目地址:http://www.lintcode.com/zh-cn/problem/majority-number/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值