找出有序数组中绝对值最小的数

var arr = [-20,-13,-4,6,77,200]

var findAbsMin= function(arr) {
    let low = 0, high = arr.length - 1;
    while (low <= high) {
        let mid = Math.floor((low + high) / 2)
        if (arr[mid] == 0) {
            return 0
        }
        if (arr[mid] < 0) {
            if (arr[mid + 1] < 0) {
                low = mid + 1
            } else {
                return Math.abs(arr[mid]) < Math.abs(arr[mid + 1]) ? arr[mid] : arr[mid + 1]
            }
        }
        if (arr[mid] > 0) {
            if (arr[mid - 1] > 0) {
                high = mid - 1
            } else {
                return Math.abs(arr[mid]) < Math.abs(arr[mid - 1]) ? arr[mid] : arr[mid - 1]
            }
        }
    }
}

findAbsMin(arr)

https://www.cnblogs.com/leezhxing/p/5468891.html

posted @ 2020-09-28 03:08  樱风凛  阅读(169)  评论(0编辑  收藏  举报