Maximum Gap
来源:互联网 发布:侠客风云传前传 mac 编辑:程序博客网 时间:2024/06/06 09:11
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.
class Solution {public: int maximumGap(vector<int>& nums) { int n = nums.size(); if (n < 2) { return 0; } int maxVal = nums[0]; int minVal = nums[0]; for (int i = 1; i < n; i++) { if (nums[i] > maxVal) { maxVal = nums[i]; } else if (nums[i] < minVal) { minVal = nums[i]; } } int bucketSize = max(1, (maxVal-minVal)/(n-1));//桶排序 int bucketNum = (maxVal-minVal)/bucketSize + 1; int counter[bucketNum]; int maxElement[bucketNum]; int minElement[bucketNum]; for (int i = 0; i < bucketNum; i++) { counter[i] = 0; maxElement[i] = minVal; minElement[i] = maxVal; } for (int i = 0; i < n; i++) { int id = (nums[i]-minVal)/bucketSize; counter[id]++; if (nums[i] > maxElement[id]) { maxElement[id] = nums[i]; } if (nums[i] < minElement[id]) { minElement[id] = nums[i]; } } int prevMax = minVal; int result = 0; for (int i = 0; i < bucketNum; i++) { if (counter[i] > 0) { int temp = minElement[i] - prevMax; if (temp > result) { result = temp; } prevMax = maxElement[i]; } } return result; }};
0 0
- Maximum Gap
- Maximum Gap
- Maximum Gap
- MAXIMUM GAP
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- POJ-3646 The Dragon of Loowater
- ecshop促销剩余时间 的函数调用方法
- Vlc播放rtsp视频
- MIT算法导论——第七讲.哈希表
- c++程序设计——实验3
- Maximum Gap
- 10个帮程序员减压放松的网站!
- 黑马程序员--学习日志4--JAVA循环体语句和控制跳转语句
- Leetcode Happy Number
- BNUOJ 1010 Deli Deli
- linux shell的一些技巧(一)使用{X..Y}以及${!XXX}
- XSLFO BLOCK
- (9-4)词库分词
- c++程序设计——实验2