zoukankan      html  css  js  c++  java
  • JZ37 数字在排序数组中出现的次数

    数字在排序数组中出现的次数

    题目:统计一个数字在升序数组中出现的次数。

    思路:排序数组,使用二分查找找区间,先找第一次出现的位置,再找第二次出现的问题,相减即可。

    func GetNumberOfK (A []int, target int) int {
        // write your code here
        if len(A) == 0 {
            return 0
        }
        // start position
        res := []int{-1, -1}
        start := 0
        end := len(A) - 1
        for start + 1 < end {
            mid := start + (end -start) / 2
            if A[mid] == target {
                end = mid
            } else if A[mid] < target {
                start = mid
            } else {
                end = mid
            }
        }
        if A[start] == target {
            res[0] = start
        }else if A[end] == target {
            res[0] = end
        } else {
            res[0] = -1
        }
    
        // end position
        start = 0
        end = len(A) - 1
        for start + 1 < end {
            mid := start + (end -start) / 2
            if A[mid] == target {
                start = mid
            } else if A[mid] < target {
                start = mid
            } else {
                end = mid
            }
        }
        if A[end] == target {
            res[1] = end
        } else if A[start] == target {
            res[1] = start
        } else {
            res[1] = -1
        }
        cnt := 0
        if res[0] != -1 && res[1] != -1 {
            cnt = res[1] - res[0] + 1
        }
        return cnt
    }
  • 相关阅读:
    margin、padding单位百分比
    Javascript CustomEvent
    javascript 复制数组
    gulp 小坑一个
    Gulp livereload
    node入门笔记
    jQuery操作input改变value属性值
    阅读笔记-A Message To Garcia
    读书笔记-忆见未来
    js this pointer 指针
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/14640975.html
Copyright © 2011-2022 走看看