164. Maximum Gap
1. 题目
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 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
2. 题目分析
一开始看错题目了,还以为是排序后,找某个差值数量最多的那个(英语渣的悲剧),后面一直提交发现都有用例过不去,然后重新读题目,发现只要找差值最大的那个,这不是so easy吗?不明白为什么这题也是middle难度。
3. 解题思路
先排序,然后遍历找最大差值。
4. 代码实现(java)
package com.algorithm.leetcode.sort;
import java.util.Arrays;
/**
* Created by 凌 on 2019/1/19.
* 注释:164. Maximum Gap
*/
public class MaximumGap {
public static void main(String[] args) {
// int[] nums = {3,6,9,1};
int[] nums = {15252,16764,27963,7817,26155,20757,3478,22602,20404,6739,16790,10588,16521,6644,20880,15632,27078,25463,20124,15728,30042,16604,17223,4388,23646,32683,23688,12439,30630,3895,7926,22101,32406,21540,31799,3768,26679,21799,23740};
int count = maximumGap(nums);
System.out.println(count);
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d \t",nums[i]);
}
}
public static int maximumGap(int[] nums) {
if (nums == null || nums.length <2){
return 0;
}
Arrays.sort(nums);
int difference = 0;
for (int i = 1; i < nums.length; i++) {
if (difference < nums[i] - nums[i-1]){
difference=nums[i] - nums[i-1];
}
}
return difference;
}
}