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 }