zoukankan      html  css  js  c++  java
  • 面试题:无序数组排序后的最大相邻差

    • 基础版本,先排序,再计算相邻差
    // 排序,然后计算最大差值
    function maxSortedNear(arr) {
        arr.sort((a, b) => a - b)
    
        let max = arr[0]
        for (let i = 1; i < arr.length; i++) {
            if (arr[i] - arr[i - 1] > max) {
                max = arr[i] - arr[i - 1]
            }
        }
        return max;
    }
    let a = [12, 3, 34, 23, 12, 2, 123]
    console.log(a.join(','));
    console.log('maxSortedNear:', maxSortedNear(a));
    
    • 优化版,使用桶排序计算
    //  优化版,使用桶排序统计最大最小值
    function maxSortedNear2(arr) {
    
        let max = arr[0]
        let min = arr[0]
        for (let i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i]
            }
            if (arr[i] < min) {
                min = arr[i]
            }
        }
    
        // 初始化桶
        let bucketNum = Math.floor((max - min) / arr.length) + 1; // 桶的数量
        let buckets = new Array(bucketNum)
        for (let i = 0; i < bucketNum; i++) {
            buckets[i] = {};
        }
    
        // 遍历数组,确定最大最小值
        for (let i = 0; i < arr.length; i++) {
            // 映射索引
            let index = Math.floor((arr[i] - min) / arr.length)
    
            let data = buckets[index]
            if (data.min === undefined || data.min > arr[i]) {
                data.min = arr[i];
            }
            if (data.max === undefined || data.max < arr[i]) {
                data.max = arr[i]
            }
        }
        // 遍历桶,找到最大差值
        let leftMax = buckets[0].max;
        let maxDistance = 0;
        for (let i = 1; i < buckets.length; i++) {
            if (buckets[i].max === undefined) {
                continue;
            }
            if (buckets[i].min - leftMax > maxDistance) {
                maxDistance = buckets[i].min - leftMax;
            }
            leftMax = buckets[i].max;
        }
        return maxDistance;
    }
    let b = [12, 3, 3, 32, 5, 5, 2, 222, 12, 42]
    console.log(b.join(','));
    console.log('maxSortedNear2:', maxSortedNear2(b));
    console.log('maxSortedNear:', maxSortedNear(b));
    console.log('maxSortedNear2:', maxSortedNear2(a));
    
  • 相关阅读:
    java中的异常类
    Mysql--JDBC的基础
    eclipse使用断言
    idea中使用断言
    java的null
    array,集合(collection),集合(list)的区别
    命名管道FIFO
    标准库中的管道操作
    现代进程间的通信方式--管道
    广播编程之发送者
  • 原文地址:https://www.cnblogs.com/songliquan/p/13152664.html
Copyright © 2011-2022 走看看