Java中等题-最大间距(力扣)

给定一个无序的数组 nums,返回 数组在排序之后,相邻元素之间最大的差值 。如果数组元素个数小于 2,则返回 0 。

您必须编写一个在「线性时间」内运行并使用「线性额外空间」的算法。

示例 1:

输入: nums = [3,6,9,1]
输出: 3
解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。

示例 2:

输入: nums = [10]
输出: 0
解释: 数组元素个数小于 2,因此返回 0。

思路:用基数排序:下面这个版本是我看了基数排序的视频之后自己写的,很多地方没有优化

class Solution {
    public int maximumGap(int[] nums) {
      if(nums.length<=1){
          return 0;
      }
      int max=1;
      for(int x:nums){
          int t=1;
          while(x/10>0){
              x/=10;
              t++;
          }
          max=Math.max(max,t);
      }

      int n=nums.length;

      for(int i=0;i<max;i++){
          int help[]=new int[n];
          int count[]=new int[10];
          for(int x:nums){
              double mal=Math.pow(10,i);
              int cal=(int)(x/mal)%10;
              count[cal]+=1;
          }
          for (int y = 1; y < 10; y++) {
              count[y] += count[y - 1];
          }
          for(int j=n-1;j>=0;j--){
              double mal=Math.pow(10,i);
              int cal=(int)(nums[j]/mal)%10;
              help[count[cal]-1]=nums[j];
              count[cal]--;

          }
          for(int z=0;z<n;z++){
              nums[z]=help[z];
          }
      }
      int ans=0;
      for(int i=1;i<n;i++){
          int t=nums[i]-nums[i-1];
          ans=Math.max(ans,t);
      }

      return ans;
    }
}

下面是力扣官方给出的答案:

class Solution {
    public int maximumGap(int[] nums) {
        int n = nums.length;
        if (n < 2) {
            return 0;
        }
        long exp = 1;
        int[] buf = new int[n];
        int maxVal = Arrays.stream(nums).max().getAsInt();

        while (maxVal >= exp) {
            int[] cnt = new int[10];
            for (int i = 0; i < n; i++) {
                int digit = (nums[i] / (int) exp) % 10;
                cnt[digit]++;
            }
            for (int i = 1; i < 10; i++) {
                cnt[i] += cnt[i - 1];
            }
            for (int i = n - 1; i >= 0; i--) {
                int digit = (nums[i] / (int) exp) % 10;
                buf[cnt[digit] - 1] = nums[i];
                cnt[digit]--;
            }
            System.arraycopy(buf, 0, nums, 0, n);
            exp *= 10;
        }

        int ret = 0;
        for (int i = 1; i < n; i++) {
            ret = Math.max(ret, nums[i] - nums[i - 1]);
        }
        return ret;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/maximum-gap/solutions/498428/zui-da-jian-ju-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值