【剑指offer】面试题39. 数组中出现次数超过一半的数字

2020.7.15

增加了新的方法,使用快排中的Partion函数实现,Partition函数每次会返回排在第j大的数及其位置,在leetcode上的前44个case可以跑通,但是不知道为什么在leetcode上的最后一个case总是超时,由于该方法会改变原始数组的顺序,因此如果不能改变顺序的这种方法不可行,还是应该采用摩尔投票法

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        return MoreThanHalfNum(nums);
    }
    int MoreThanHalfNum(vector<int>& nums) {
        int middle = nums.size() >> 1;
        int start = 0;
        int end = nums.size() - 1;
        int index = Partition(nums, start, end);
        while (index != middle) {
            if (index > middle) {
                end = index - 1;
                index = Partition(nums, start, end);
            }
            else {
                start = index + 1;
                index = Partition(nums, start, end);
            }
        }
        int result = nums[middle];
        return result;
    }
    //使主元排在第j位
    int Partition(vector<int>& nums,int s, int e) {
        int index = (rand() % (e - s + 1)) + s;
        swap(nums[index], nums[s]);
        int i = s + 1, j = e;
        while (true) {
            while (i <= j && nums[i] <= nums[s]) i++;
            while (i <= j && nums[j] >= nums[s]) j--;
            if (i > j) break;
            swap(nums[i], nums[j]);
        }
        swap(nums[j], nums[s]);
        return j;
    }
};

解题思路

利用题目所给数组特性,所求元素在数组中出现次数超过一半
设置两个变量:
result//记录当前元素值
times//记录次数
当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数+1;如果下一个数字和我们之前保存的数字不同,则次数-1.如果次数为0,那么我们需要保存下一个数字
,并把次数设为1.

代码

class Solution
{
public:
	int majorityElement(vector<int>& nums) {
		int result=nums[0];
		int times = 1;
		for (vector<int>::iterator it=nums.begin()+1;it!=nums.end();it++)
		{
			//次数为0,则更新result
			if (times == 0) {
				result = *it;
				times = 1;
			}
			//相等,次数+1
			else if(result==*it)
			{
				times++;
			}
			//不相等,次数-1
			else
			{
				times--;
			}
		}
		return result;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值