劍指offer 53 -I 在排序陣列中查詢數字
阿新 • • 發佈:2021-07-16
統計一個數字在排序陣列中出現的次數。
示例 1:
輸入: nums = [5,7,7,8,8,10], target = 8 輸出: 2
示例2:
輸入: nums = [5,7,7,8,8,10], target = 6 輸出: 0
限制:
0 <= 陣列長度 <= 50000
二分查詢
/** * 二分查詢 * * @param nums * @param target * @return */ public static int search(int[] nums, int target) { if (nums == null || nums.length == 0) return 0; int cnt = 0; int left = 0, right = nums.length - 1; int mid = left; while (left <= right) { mid = (left + right) >> 1; if (nums[mid] == target) break; else if (nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } int index = mid; // 左側 while (index >= 0 && index < nums.length && nums[index] == target) { cnt++; index--; } index = mid + 1; // 右側 while (index >= 0 && index < nums.length && nums[index] == target) { cnt++; index++; } return cnt; }
測試用例
public static void main(String[] args) { int[] nums = new int[]{0}; int target = 0; int cnt = SearchSecond.search(nums, target); System.out.println("SearchSecond demo01 result : " + cnt); nums = new int[]{5, 7, 7, 8, 8, 10}; target = 8; cnt = SearchSecond.search(nums, target); System.out.println("SearchSecond demo02 result : " + cnt); nums = new int[]{5, 7, 7, 8, 8, 10}; target = 6; cnt = SearchSecond.search(nums, target); System.out.println("SearchSecond demo03 result : " + cnt); nums = new int[]{1, 2, 3, 3, 3, 3, 4, 5, 9}; target = 3; cnt = SearchSecond.search(nums, target); System.out.println("SearchSecond demo04 result : " + cnt); nums = new int[]{1, 2, 3}; target = 1; cnt = SearchSecond.search(nums, target); System.out.println("SearchSecond demo05 result : " + cnt); }
執行結果