Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅164. 最大间距 #171

Open
Ray-56 opened this issue Nov 26, 2020 · 1 comment
Open

✅164. 最大间距 #171

Ray-56 opened this issue Nov 26, 2020 · 1 comment

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Nov 26, 2020

164. 最大间距

给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。

如果数组元素个数小于 2,则返回 0。

示例1:

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

示例2:

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

说明:

  • 你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
  • 请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。
@Ray-56
Copy link
Owner Author

Ray-56 commented Nov 26, 2020

使用 sort

/**
 * @param {number[]} nums
 * @return {number}
 */
var maximumGap = function(nums) {
    const len = nums.length;
    if (len < 2) return 0;
    nums.sort((a, b) => a - b);

    let max = -1;
    for (let i = 1; i < len; i++) {
        const val = nums[i] - nums[i - 1];
        if (val > max) {
            max = val
        }
    }
    return max;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant