题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
using System; using System.Collections.Generic; class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param data int整型一维数组 * @param k int整型 * @return int整型 */ public int GetNumberOfK (List<int> data, int k) { // write code here var index=Find(data,0,data.Count-1,k); if(index<0) return 0; int ans=1; var temp=index; while(--temp>=0) { if(data[temp]==k) ans++; else break; } while(++index<data.Count) { if(data[index]==k) ans++; else break; } return ans; } public int Find(List<int> data,int s,int e,int key) { if(s>e) return -1; int mid=(s+e)/2; if(data[mid]==key) return mid; if(data[mid]>key) return Find(data, s, mid-1, key); else return Find(data, mid+1, e, key); } } 没有采取最通用的想法,找到一个位置,往两边搜