题目:统计一个数字在排序数组中出现的次数。例如输入排序数组{1,2,3,3,3,3,4,5}和数字3,由于3在这个数组中出现了4次,因此输出4.
最简单的是一次遍历,但是更高效的方法是二分查找,需要略微改变.
核心代码:
<pre><code>`
func searchNumberOfK(arr:[Int],num:Int) -> Int? {
if arr.count == 0 {
return nil
}
let first:Int? = searchFirstOfK(arr: arr, num: num)
let last:Int? = searchLastOfK(arr: arr, num: num)
if first == nil || last == nil {
return nil
} else {
let count:Int = last! - first! + 1
return count
}
}
func searchFirstOfK(arr:[Int],num:Int) -> Int? {
var low:Int = 0
var high:Int = arr.count - 1
while low <= high {
let mid:Int = (low + high)/2
if arr[mid] > num {
high = mid - 1
} else if arr[mid] < num {
low = mid + 1
} else {
if (mid > 0 && arr[mid-1] != num) || mid == 0 {
return mid
} else {
high = mid - 1
}
}
}
return nil
}
func searchLastOfK(arr:[Int],num:Int) -> Int? {
var low:Int = 0
var high:Int = arr.count - 1
while low <= high {
let mid:Int = (low + high)/2
if arr[mid] > num {
high = mid - 1
} else if arr[mid] < num {
low = mid + 1
} else {
if (mid < arr.count - 1 && arr[mid+1] != num) || mid == arr.count - 1 {
return mid
} else {
low = mid + 1
}
}
}
return nil
}`</code></pre>
测试代码:
<pre><code>`
var sortArr:[Int] = [1,2,3,3,3,3,4,5]
var sortTarget:Int = 1
var sortCount:Int? = binarySearch.searchNumberOfK(arr: sortArr, num: sortTarget)
if sortCount == nil {
print("FlyElephant-(sortArr)不存在数字-(sortTarget)")
} else {
print("FlyElephant-(sortArr)中数字-(sortTarget)的次数--(sortCount!)")`</code></pre>