Hard-题目16:164. Maximum Gap

本文提供了一种解决方案,用于找出给定无序数组在排序后相邻元素间的最大差距。通过直接排序并遍历数组来计算最大差值,适用于非负整数且数量不超过32位整数范围的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目原文:
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.
题目大意:
给出一个无序的数组,求出排序后相邻两个元素差的最大值。如果数组长度小于2,则返回0.
题目分析:
懒得做了,直接按题面要求做。
源码:(language:java)

public class Solution {
    public int maximumGap(int[] nums) {
        if(nums.length<2)
            return 0;
        Arrays.sort(nums);
        int maxgap = Integer.MIN_VALUE;
        for(int i = 1;i<nums.length;i++) {
            if(nums[i]-nums[i-1]>maxgap)
                maxgap=nums[i]-nums[i-1];
        }
        return maxgap;
    }
}

成绩:
4ms,beats 92.15%,众数6ms,27.29%
Cmershen的碎碎念:
不知道leetcode后台的test case怎么设计的,有很多题用朴素解法比绞尽脑汁想出的低复杂度算法还要快。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值