[Leetcode] #164 Maximum Gap

本文介绍了一种线性时间和空间复杂度的算法,用于找到未排序数组中排序后相邻元素的最大间隔。该算法首先确定数组中的最小和最大值,然后通过桶排序的方式计算最大间隔。

Discription

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

Solution

int maximumGap(vector<int> &num) {
	if (num.size() < 2)
		return 0;
	int size = num.size();
	int Min = num[0];
	int Max = num[0];
	for (int i = 1; i < size; ++i){
		Max = max(Max, num[i]);
		Min = min(Min, num[i]);
	}
	int gap = (Max - Min) / (size - 1) + 1;
	int bucketNum = (Max - Min) / gap + 1;
	vector<int> bucketsMin(bucketNum, INT_MAX);
	vector<int> bucketsMax(bucketNum, INT_MIN);
	for (int i = 0; i < size; ++i){
		if (num[i] == Max || num[i] == Min)
			continue;
		int index = (num[i] - Min) / gap;
		bucketsMin[index] = min(bucketsMin[index], num[i]);
		bucketsMax[index] = max(bucketsMax[index], num[i]);
	}
	int maxGap = 0;
	int pre = Min;
	for (int i = 0; i < bucketNum; ++i){
		if (bucketsMin[i] == INT_MAX || bucketsMax[i] == INT_MIN)
			continue;
		maxGap = max(maxGap, bucketsMin[i] - pre);
		pre = bucketsMax[i];
	}
	maxGap = max(maxGap, Max - pre);
	return maxGap;
}
GitHub-Leetcode: https://github.com/wenwu313/LeetCode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值