首页 > 试题广场 >

最大差值(二)

[编程题]最大差值(二)
  • 热度指数:390 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个长度为 n 的数组,请你计算这个数组排序后所有相邻数字最大差值。请考虑线性复杂度的做法。

数据范围:,数组中的值都满足
示例1

输入

[5,3,4,5,7]

输出

2

说明

排序后的数组是 3 4 5 5 7 ,最大差值是 2 
package main
import "sort"

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param nums int整型一维数组 
 * @return int整型
*/
func maxGap( nums []int ) int {
    sort.Ints(nums)
    max:=0
    for i,x:=range nums{
        if i>0{
            if x-nums[i-1]>max{
                max=x-nums[i-1]
            }
        }
    }
    return max
}

发表于 2023-03-16 13:29:43 回复(0)
class Solution {
  public:
    int maxGap(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int z = 0;     
        for (int i = 0, j = 1; j < nums.size(); i++, j++) {z = max(nums[j] - nums[i], z);}
        return z;
    }
};

发表于 2022-07-25 11:05:27 回复(0)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型ArrayList 
     * @return int整型
     */
    public int maxGap(ArrayList<Integer> nums) {
        // write code here
        Collections.sort(nums);

        int max = Integer.MIN_VALUE;
        for (int i = 1; i < nums.size(); i++) {
            max = Math.max(max, nums.get(i) - nums.get(i - 1));
        }
        return max;
    }
}

发表于 2022-04-28 21:22:43 回复(0)

问题信息

难度:
3条回答 1769浏览

热门推荐

通过挑战的用户

查看代码