【分治算法】Leetcode编程题解:169. Majority Element Add to List

题目:

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

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

这道题目本来可以用哈希表来解决,不过题目要求用分治算法的思想,所以没有使用。因为想不出将该问题拆分为小问题的方法,所以参考了网上的思路,采用一种似乎不是很常规的分治算法(感觉跟标准的分治还是有点区别)。这种方法是基于如果一个数在这个数组中是出现次数最多的,那么在删去一对不同的数后剩下的子数组中,该数也是出现次数最多的。这种算法名为Moore Voting Algorithm

提交代码:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int index = 0, count = 1;
        for(int i = 1; i < nums.size(); i++) {
        	if(nums[i] == nums[index])
        	count++;
        	else
        	count--;
        	if(count == 0) {
        		count = 1;
        		index = i;
			}
		}
		return nums[index];
    }
};

这道题目还有延伸,也就是返回该数组中所有的出现次数超过k次的数(k小于n/2)。

可以参考以下网址:

http://www.cnblogs.com/JimmyTY/p/5020871.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值