LeetCode 164 Maximum Gap (C++, Python)
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 C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Solution { void radixSort(vector<int>&num, int exp) { vector<int>output(num.size(), 0); int count[10] = {0}; for (int n: num) { count[n / exp % 10] ++; } for (int i = 1; i < 10; ++i) { count[i] += count[i - 1]; } for (auto it = num.rbegin(); it != num.rend(); ++it) { output[count[*it / exp % 10] - 1] = *it; count[*it / exp % 10] --; } num = output; } public: int maximumGap(vector<int> &num) { int diff = 0; if (num.size() < 2) return diff; int upper = *max_element(num.begin(), num.end()); for (int exp = 1; upper / exp > 0; exp *= 10) { radixSort(num, exp); } for (int i = 1; i < num.size(); ++i) { diff = max(diff, num[i] - num[i - 1]); } return diff; } }; |
Solution Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | class Solution: def radixSort(self, num): upper = max(num) exp = 1 while True: if upper / exp == 0: break self.counterSort(num, exp) exp *= 10 def counterSort(self, num, exp): output = [0] * len(num) counter = [0] * 10 for n in num: counter[n / exp % 10] += 1 for i in range(1, 10): counter[i] += counter[i - 1] for i in range(len(num) - 1, -1, -1): output[counter[num[i] / exp % 10] - 1] = num[i] counter[num[i] / exp % 10] -= 1 num[:] = output # @param num, a list of integer # @return an integer def maximumGap(self, num): diff = 0; if len(num) < 2: return diff self.radixSort(num) for i in range(1, len(num)): diff = max(diff, num[i] - num[i - 1]) return diff |