题目:统计一个数字在排序数组中出现的次数。例如输入排序数组{1,2,3,3,3,3,4,5}和数字3,由于3在这个数组中出现了4次,因此输出4。
程序实现:
import java.util.Scanner; public class Test38 { public static void main(String[] args) { /** * 初始化数组,测试数据可以多种途径初始化 */ Scanner in = new Scanner(System.in); /*int[] a = new int[8]; for(int i=0;i<8;i++){ a[i] = in.nextInt(); }*/ /** * 多个测试用例 */ int[] a = {1,2,3,3,3,3,4,5}; //int[] a = {1, 2, 3, 3, 3, 3}; //int[] a = {3}; int key = in.nextInt(); /** * 调用函数 */ Test38 t = new Test38(); int num = t.sortN(a,key); System.out.println(num); } private int sortN(int[] a,int key){ int sum = 0; /** * 数组长度鲁棒性检查 */ if(a.length == 0){ return 0; } Test38 t = new Test38(); /** * getFirstK和getLastK两个都是二分查找,他们的时间复杂度都是O(logN) */ int firstK = t.getFirstK(a, key, 0, a.length); int lastK = t.getLastK(a, key, 0, a.length); if(firstK != -1 && lastK != -1){ sum = lastK - firstK + 1; } return sum; } //递归写法 private int getFirstK(int [] array , int k, int start, int end){ /** * 鲁棒性检查 */ if(start > end){ return -1; } int mid = (start + end) >> 1; if(array[mid] > k){ return getFirstK(array, k, start, mid-1); }else if (array[mid] < k){ return getFirstK(array, k, mid+1, end); }else if(mid-1 >=0 && array[mid-1] == k){ return getFirstK(array, k, start, mid-1); }else{ return mid; } } //循环写法 private int getLastK(int [] array , int k, int start, int end){ /** * 鲁棒性检查 */ int length = array.length; int mid = (start + end) >> 1; while(start <= end){ if(array[mid] > k){ end = mid-1; }else if(array[mid] < k){ start = mid+1; }else if(mid+1 < length && array[mid+1] == k){ start = mid+1; }else{ return mid; } mid = (start + end) >> 1; } return -1; } }
时间: 2024-10-20 21:18:36