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
    }
  • 相关阅读:
    css3多列
    伪元素
    text文本样式二
    透明登录框
    透明度设置opacity
    超链接
    meta标签
    奇偶选择器
    OC跟Swift混编
    Swift中as as! as?的区别
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/14640975.html
Copyright © 2011-2022 走看看