【LeetCode】164.Maximum Gap(Hard)解题报告
2018-03-02 15:12
375 查看
【LeetCode】164.Maximum Gap(Hard)解题报告
题目地址:https://leetcode.com/problems/maximum-gap/description/
题目描述:
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:
Date:2018年3月2日
题目地址:https://leetcode.com/problems/maximum-gap/description/
题目描述:
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:
/* 看到排序,还要求线性时间空间复杂度,就要想到桶排序,bucket sort。 挺难的一道题,目的是找到排序之后的最大间隔。 1 3 5 9 min = 1 max = 9 gap = 3 1 4 7 9 bucketsMin: 3 5 INF 区间中的最小值 bucketsMax: 3 5 -INF 区间中的最大值 time : O(n) space : O(n) */ class Solution { public int maximumGap(int[] nums) { if(nums == null || nums.length < 2) return 0; int len = nums.length; int min = nums[0]; int max = nums[0]; for(int i=0 ; i<nums.length ; i++){ min = Math.min(min , nums[i]); max = Math.max(max , nums[i]); } int gap = (int)Math.ceil((double)(max - min)/(len - 1)); int[] bucketsMin = new int[len - 1]; int[] bucketsMax = new int[len - 1]; Arrays.fill(bucketsMin , Integer.MAX_VALUE); Arrays.fill(bucketsMax , Integer.MIN_VALUE); for(int num : nums){ if(num == min || num == max) continue; int bucket = (num -min)/gap; //看在哪个区间里 bucketsMin[bucket] = Math.min(num , bucketsMin[bucket]); bucketsMax[bucket] = Math.max(num , bucketsMax[bucket]); } int res = 0; int pre = min; for(int i=0 ; i<len-1 ; i++){ //区间里数没有 if(bucketsMin[i] == Integer.MAX_VALUE && bucketsMax[i] == Integer.MIN_VALUE){ continue; } res = Math.max(res , bucketsMin[i] - pre); pre = bucketsMax[i]; } //下面这句别忘了,最大值还没算 res = Math.max(res , max-pre); return res; } }
Date:2018年3月2日
相关文章推荐
- 【LeetCode】52.N-Queens II(hard)解题报告
- 【LeetCode】297.Serialize and Deserialize Binary Tree(Hard)解题报告
- 【LeetCode】135.Candy(hard)解题报告
- 【LeetCode】291.Word Pattern II(Hard)解题报告
- 【LeetCode】282.Expression Add Operators(Hard)解题报告
- 【LeetCode】45.Jump Game II(Hard)解题报告
- 【LeetCode】51.N-Queens(hard)解题报告
- 【LeetCode】4.Median of Two Sorted Arrays(Hard)解题报告
- 【LeetCode】42.Trapping Rain Water(Hard)解题报告
- 【LeetCode】726.Number of Atoms(Hard)解题报告
- 【LeetCode】301.Remove Invalid Parentheses(hard)解题报告
- 【LeetCode】41. First Missing Positive(Hard)解题报告
- 【LeetCode】99.Recover Binary Search Tree(Hard)解题报告
- 【LeetCode】330.Patching Array(Hard)解题报告
- 【LeetCode】321.Create Maximum Number(Hard)解题报告
- 【LeetCode】664.Strange Printer(hard)解题报告
- 【LeetCode】327. Count of Range Sum(Hard)解题报告
- 【LeetCode】403. Frog Jump(Hard)解题报告
- 【LeetCode】10.Regular Expression Matching(hard)解题报告
- 【LeetCode】145.Binary Tree Postorder Traversal(Hard)解题报告