LintCode 400: Maximum Gap (bucket sort经典题!)

本文介绍了一种在O(n)时间和空间复杂度内寻找数组中最大元素间隔的方法。通过将数组分为若干个桶(bucket),并利用桶排序的思想来高效地解决此问题。
  1. Maximum Gap

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

Return 0 if the array contains less than 2 elements.

Example
Given [1, 9, 2, 5], the sorted form of it is [1, 2, 5, 9], the maximum gap is between 5 and 9 = 4.

Challenge
Sort is easy but will cost O(nlogn) time. Try to solve it in linear time and space.

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

解法1:bucket sorting
这题我想了半天,什么双指针,单调栈,DP都想了,最后觉得如果要时间复杂度和空间复杂度都是O(n)的话只能用类似bucket sort之类的方法。
首先是找到min和max,然后将其分成k份。这个k有讲究,不能超过n,但是也不能小于maxV-minV。所以取min(n, maxV-minV)。假如maxV-minV很小,则所有元素都挤在几个数上,那么最多也只能有maxV-minV个buckets。
然后我们分析一下就可以知道,相邻元素间隔最大值只可能是某个bucket的最大元素和下一个bucket的最小元素。那么为什么不可能是某个bucket里面的两个元素呢?因为我们将n个元素分到<=n个buckets里面,所以某个bucket最多分到一个元素!
那么可不可以分maxV-minV+1个buckets呢?可能可以,没有试。

注意:

  1. 特殊情况:
    a. 所有元素均相同 [1,1,1,1,1,1,1],此时返回0即可。
    b. 最大元素比最小元素大1 [1,1,1,1,1,2,1,1],此时返回1即可。因为maxV-minV=1,只能有1个bucket,下面的代码不适用。
  2. 因为map的原则都是往最近的大于等于该元素的bucket去map,最大的那个元素要特殊处理,应该map到bucket[bucketNum - 1]。
    代码如下:
struct bucketType {
    int count;
    int minNum;
    int maxNum;
    bucketType(int c = 0, int minV = INT_MAX, int maxV = 0) : count(c), minNum(minV), maxNum(maxV) {}
};

class Solution {
public:
    /**
     * @param nums: an array of integers
     * @return: the maximun difference
     */
    int maximumGap(vector<int> &nums) {
        int n = nums.size();
        if (n < 2) return 0;
        
        int minV = INT_MAX, maxV = INT_MIN;
        
        for (int i = 0; i < n; ++i) {
            minV = min(minV, nums[i]);
            maxV = max(maxV, nums[i]);
        }
        
        //special case [1,1,1,2,1,1], [1,1,1,1,1,1]
        if (maxV - minV <= 1) return maxV - minV; 
        
        int bucketNum = min(n, maxV - minV);   //important!!!
        int bucketLen = (maxV - minV) / bucketNum;
        vector<bucketType> buckets(bucketNum);
        
        // the buckets are [ ) range
        for (int i = 0; i < n; ++i) {
            int index = (nums[i] - minV) / bucketLen;
            if (index >= bucketNum) index = bucketNum - 1;
  
            buckets[index].count++;
            buckets[index].maxNum = max(buckets[index].maxNum, nums[i]);
            buckets[index].minNum = min(buckets[index].minNum, nums[i]);
        }

        int maxDist = 0;
        int lastElem = buckets[0].maxNum;
        for (int i = 1; i < bucketNum; ++i) {
            if (buckets[i].count == 0) continue;
            maxDist = max(maxDist, buckets[i].minNum - lastElem);
            lastElem = buckets[i].maxNum;
        }
        return maxDist;
    }
};
根据原作 https://pan.quark.cn/s/459657bcfd45 的源码改编 Classic-ML-Methods-Algo 引言 建立这个项目,是为了梳理和总结传统机器学习(Machine Learning)方法(methods)或者算法(algo),和各位同仁相互学习交流. 现在的深度学习本质上来自于传统的神经网络模型,很大程度上是传统机器学习的延续,同时也在不少时候需要结合传统方法来实现. 任何机器学习方法基本的流程结构都是通用的;使用的评价方法也基本通用;使用的一些数学知识也是通用的. 本文在梳理传统机器学习方法算法的同时也会顺便补充这些流程,数学上的知识以供参考. 机器学习 机器学习是人工智能(Artificial Intelligence)的一个分支,也是实现人工智能最重要的手段.区别于传统的基于规则(rule-based)的算法,机器学习可以从数据中获取知识,从而实现规定的任务[Ian Goodfellow and Yoshua Bengio and Aaron Courville的Deep Learning].这些知识可以分为四种: 总结(summarization) 预测(prediction) 估计(estimation) 假想验证(hypothesis testing) 机器学习主要关心的是预测[Varian在Big Data : New Tricks for Econometrics],预测的可以是连续性的输出变量,分类,聚类或者物品之间的有趣关联. 机器学习分类 根据数据配置(setting,是否有标签,可以是连续的也可以是离散的)和任务目标,我们可以将机器学习方法分为四种: 无监督(unsupervised) 训练数据没有给定...
### Bubble Sort The core idea of bubble sort is to repeatedly traverse the list to be sorted. In each iteration, it compares two adjacent elements and swaps them if they are in the wrong order. Through multiple passes, the largest (or smallest) elements gradually "bubble" to the end of the list until the entire list is sorted. ```python def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr ``` ### Selection Sort Selection sort works by finding the minimum (or maximum) element from the unsorted part of the list and placing it at the beginning of the unsorted part. This process is repeated until the entire list is sorted. ```python def selection_sort(arr): for i in range(len(arr)): min_idx = i for j in range(i + 1, len(arr)): if arr[j] < arr[min_idx]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i] return arr ``` ### Insertion Sort Insertion sort inserts each unsorted element into its correct position within the already sorted part of the list. Initially, the sorted part contains only the first element, and then elements are inserted one by one to keep the sorted part ordered. ```python def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr ``` ### Shell Sort Shell sort divides the entire list into several sub - lists and performs direct insertion sort on these sub - lists. As the algorithm progresses, the list becomes more and more "nearly sorted", and finally, a direct insertion sort is performed on the whole list. ```python def shell_sort(arr): n = len(arr) gap = n // 2 while gap > 0: for i in range(gap, n): temp = arr[i] j = i while j >= gap and arr[j - gap] > temp: arr[j] = arr[j - gap] j -= gap arr[j] = temp gap //= 2 return arr ``` ### Merge Sort Merge sort follows the divide - and - conquer strategy. It divides the list into two sub - lists, sorts these two sub - lists separately, and then merges the sorted sub - lists into a final sorted list. ```python def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 return arr ``` ### Quick Sort Quick sort selects a pivot element, partitions the list into two parts such that all elements in the left part are less than or equal to the pivot, and all elements in the right part are greater than or equal to the pivot. Then it recursively sorts the left and right parts. ```python def quick_sort(arr): if len(arr) <= 1: return arr else: pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_sort(right) ``` ### Heap Sort Heap sort uses the heap data structure. A heap is a nearly complete binary tree that satisfies the heap property. First, it builds a max - heap (or min - heap) from the array. Then, it repeatedly swaps the root of the heap (the largest or smallest element) with the last element of the heap, reduces the size of the heap, and adjusts the heap to maintain the heap property until the entire array is sorted. ```python import heapq def heap_sort(arr): heapq.heapify(arr) return [heapq.heappop(arr) for _ in range(len(arr))] ``` ### Counting Sort Counting sort determines the number of elements less than each element \(x\) in the input list. Then, it places \(x\) directly into the correct position in the final sorted list. ```python def counting_sort(arr): max_val = max(arr) count = [0] * (max_val + 1) for num in arr: count[num] += 1 sorted_arr = [] for i in range(len(count)): sorted_arr.extend([i] * count[i]) return sorted_arr ``` ### Bucket Sort Bucket sort divides the array into a finite number of buckets. Each bucket is then sorted individually (possibly using another sorting algorithm or recursively applying bucket sort). Finally, the elements from each bucket are concatenated to form the sorted list. ```python def bucket_sort(arr): num_buckets = 10 buckets = [[] for _ in range(num_buckets)] for num in arr: index = int(num * num_buckets) buckets[index].append(num) for bucket in buckets: bucket.sort() sorted_arr = [] for bucket in buckets: sorted_arr.extend(bucket) return sorted_arr ``` ### Radix Sort Radix sort sorts integers by processing individual digits. It starts from the least significant digit and sorts the numbers according to each digit position. After sorting by each digit, the numbers become sorted in ascending order. ```python def radix_sort(arr): max_num = max(arr) exp = 1 while max_num // exp > 0: counting_sort_for_radix(arr, exp) exp *= 10 return arr def counting_sort_for_radix(arr, exp): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = arr[i] // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = n - 1 while i >= 0: index = arr[i] // exp output[count[index % 10] - 1] = arr[i] count[index % 10] -= 1 i -= 1 for i in range(n): arr[i] = output[i] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值