标签:查找 ret 个数 length array ast bsp color ber
题目
统计一个数字在排序数组中出现的次数。
分析
利用二分查找,找到该数字第一次出现的位置和最后一次出现的位置。
代码
1 public int GetNumberOfK(int[] array, int k){ 2 int first = GetFirst(array, k, 0, array.length-1); 3 int last = GetLast(array, k, 0, array.length-1); 4 if(first==-1 || last==-1) 5 return 0; 6 return last-first+1; 7 } 8 9 public int GetFirst(int[] array, int k, int low, int high){ 10 int tag = -1; 11 12 while(low<=high){ 13 int mid = (low+high)/2; 14 if(array[mid]>k){ 15 high = mid-1; 16 } 17 else if(array[mid]<k){ 18 low = mid+1; 19 } 20 else{ 21 if(mid==0 || (mid>0 && (array[mid-1]<array[mid]))){ 22 tag = mid; 23 break; 24 } 25 else{ 26 high = mid-1; 27 } 28 } 29 } 30 return tag; 31 } 32 33 public int GetLast(int[] array, int k, int low, int high){ 34 int tag = -1; 35 while(low<=high){ 36 int mid = (low+high)/2; 37 if(array[mid]>k) 38 high = mid-1; 39 else if(array[mid]<k) 40 low = mid+1; 41 else{ 42 if(mid==array.length-1 || (mid<array.length-1 && (array[mid]<array[mid+1]))){ 43 tag = mid; 44 break; 45 } 46 else{ 47 low = mid+1; 48 } 49 } 50 } 51 return tag; 52 }
标签:查找 ret 个数 length array ast bsp color ber
原文地址:http://www.cnblogs.com/jiqianqian/p/6955728.html