164. Maximum Gap

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;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值