// 非递归方式 public int binarySearch(int[] nums, int target){ int left = 0, right = target.length -1; while(left <= right){ int mid = left + (right - left) / 2; if(nums[mid] < target){ left = mid + 1; } else if(nums[mid] > target) { right = mid - 1; } else { return mid; } } return left; } // 递归方式 public int binarySearch(int[] nums, int target, int left, int right){ if(left > right){ return left; } int mid = left + (right - left) / 2; if(nums[mid] < target){ return binarySearch(nums, target, mid+1, right); } else if(nums[mid] > target){ return binarySearch(nums, target, left, mid-1); } else { return mid; } }
// 非递归方式 public int binarySearchFirst(int[] nums, int target){ int left = 0, right = target.length -1; while(left <= right){ int mid = left + (right - left) / 2; if(nums[mid] < target){ left = mid + 1; } else if (nums[mid] >= target) { right = mid - 1; } } return left; } //递归方式 public int binarySearchFirst(int[] nums, int target, int left, int right){ if(left > right){ return left; } int mid = left + (right - left) >> 1; if(nums[mid] < target){ return binarySearchFirst(nums, target, mid+1, right); } else if(nums[mid] >= target){ return binarySearchFirst(nums, target, left, mid-1); } }