LeetCode-169.229. Majority Element II (JAVA)主要元素

169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appearsmore than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

从一个数组中找出出现半数以上的元素。(数组肯定存在这样的元素)

排序:

返回中间元素

// Sorting
public int majorityElement(int[] nums) {
    Arrays.sort(nums);
    return nums[nums.length/2];
}
Hashtable(jdk8语法)

	public int majorityElement(int[] nums) {
	    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
	    int ret=0;
	    for (int num: nums) {
	    	map.put(num, map.getOrDefault(num, 0)+1);
	        if (map.get(num)>nums.length/2) {
	            ret = num;
	            break;
	        }
	    }
	    return ret;
	}
}
Moore voting algorithm   

每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。

当然,最后剩下的元素也可能并没有出现半数以上。比如说数组是[1, 2, 3],最后剩下的3显然只出现了1次,并不到半数。排除这种false positive情况的方法也很简单,只要保存下原始数组,最后扫描一遍验证一下就可以了。

public int majorityElement(int[] nums) {
        int count = 0, ret = 0;
        for (int num : nums) {
            if (count == 0)
                ret = num;
            if (num != ret)
                count--;
            else
                count++;
        }
        return ret;
    }


229. Majority Element II

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.

借鉴上一题的        Moore voting algorithm   

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

三三抵消,最后会剩下两个candidates,但是注意此时不是谁占多数谁是最终结果,反例[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 4, 4] 三三抵消后剩下 [1, 4,4] 4数量占优,但结果应该是1,所以三三抵消后,再loop一遍找1和4谁数量超过了len(nums)/3

	public List<Integer> majorityElement(int[] nums) {
		List<Integer> ret = new ArrayList<>();
		int n = nums.length;
		int candidate1 = 0, candidate2 = 0, counter1 = 0, counter2 = 0;
		for (int i : nums) {
			if (candidate1 == i) {
				counter1++;
			} else if (candidate2 == i) {
				counter2++;
			} else if (counter1 == 0) {
				candidate1 = i;
				counter1 = 1;
			} else if (counter2 == 0) {
				candidate2 = i;
				counter2 = 1;
			} else {
				counter1--;
				counter2--;
			}
		}
		// 统计数量多的,最后剩下元素
		counter1 = 0;
		counter2 = 0;
		for (int num : nums) {
			if (num == candidate1)
				counter1++;
			else if (num == candidate2)
				counter2++;
		}
		if (counter1 > n / 3)
			ret.add(candidate1);
		// 不能直接else,可能为空集
		if (counter2 > n / 3)
			ret.add(candidate2);
		return ret;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值