Advertisement
Dmaxiya

binarySearch 递归写法

Sep 17th, 2022
842
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.87 KB | None | 0 0
  1. //Given an array of integers nums which is sorted in ascending order,
  2. // and an integer target, write a function to search target in nums.
  3. // If target exists, then return its index. Otherwise, return -1.
  4. //
  5. //You must write an algorithm with O(log n) runtime complexity
  6.  
  7. public class Solution {
  8.     public int search(int[] nums, int target) {
  9.         return binarySearch(nums, 0, nums.length, target);
  10.     }
  11.  
  12.     public int binarySearch(int[] nums, int l, int r, int target) {
  13.         if (l == r) {
  14.             return -1;
  15.         }
  16.         if (r - l == 1) {
  17.             if (nums[l] != target) {
  18.                 return -1;
  19.             }
  20.             return l;
  21.         }
  22.  
  23.         int mid = (l + r) / 2;
  24.         if (nums[mid] > target) {
  25.             return binarySearch(nums, l, mid, target);
  26.         }
  27.         return binarySearch(nums, mid, r, target);
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement