Leetcode 414.第三大的数

这一题由两种方法:1. 快排法,直接找出第三个位置的数 2. 直接利用STL库,直接nth_element。
注意:这一题所得第k大的数,表示非重复第k大,在程序执行之前需要去重。
第一种方法:

  1. 在快排中,我们有一个条件约束,就是每一次的对比索引如果比K(需要找的第K大数)大,则表明此数在左半部分,否则则在右半部分
  2. 然后根据快排更改,写出满足约束条件的快排搜索
//快排(降序)搜寻第K大的数
void SearchKthOfQS(vector<int>& nums, int start, int end, int k) {
	//搜索按序(降序)后位于第三个位置的数。
	if (start + 1 >= end)
		return;
	int conindex = start;
	int left = start, right = end - 1;
	while (left < right) {
		while (right >start && nums[right] <= nums[conindex])
			--right;
		if(right >= conindex)
			swap(nums[conindex], nums[right--]),
			conindex = right+1;
		while (nums[left] > nums[conindex] &&left<end)
			++left;
		if (left <= conindex)
			swap(nums[conindex], nums[left++]),
			conindex = left-1;
	}

	if (conindex == k) 
		return;
	else if (conindex > k)
		SearchKthOfQS(nums, start, conindex, k);
	else
		SearchKthOfQS(nums, conindex + 1, end, k);
}

第二种方法:直接利用STL

int thirdMax(vector<int>& nums, int k=3) {
	在这leetcode中,第三大的数,是第三大并不是按序第三个
	在这里,方法一使用快排搜索位于第三大的数,但必须去重
	set<int> se;
	for (int i = 0; i < nums.size(); ++i) {
		if (se.count(nums[i]) == 0)
			se.insert(nums[i]);
		else
			nums.erase(nums.begin() + i--);
	}
	//if (nums.size() == 3)
	//	return *min_element(nums.begin(), nums.end());
	//if (nums.size() < 3)
	//	return *max_element(nums.begin(), nums.end());
	//SearchKthOfQS(nums, 0, nums.size(), k - 1);
	//return nums[k-1];
	
	//也可以直接使用STL,nth_element
	if (nums.size() < 3)
		return *max_element(nums.begin(), nums.end());
	nth_element(nums.begin(), nums.begin() + 2, nums.end(), [](int a, int b) {return a > b; });
	return nums[3-1];
}

附Python代码:

    def SearchKthOfBS(self, nums, start, end, k):
        if start +1 >= end:
            return
        conindex, left, right = start, start, end-1

        while left < right:
            while right>=start and nums[right] <= nums[conindex]:
                right-=1
            if right >= conindex:
                nums[conindex], nums[right]=nums[right], nums[conindex]
                conindex ,right = right, right - 1

            while left<end and nums[left] >= nums[conindex]:
                left+=1
            if left <= conindex:
                nums[conindex], nums[left]=nums[left], nums[conindex]
                conindex ,left = left, left + 1

        if conindex == k:
            return
        elif conindex >k:
            self.SearchKthOfBS(nums, start, conindex, k)
        else:
            self.SearchKthOfBS(nums, conindex+1, end, k)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值