Advertisement
Dmaxiya

binarySearch while 写法

Sep 18th, 2022
803
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 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.         int l = -1;
  10.         int r = nums.length;
  11.         int mid;
  12.         // 二分查找大于等于 target 值的最小下标
  13.         while (r - l > 1) {
  14.             mid = (l + r) / 2;
  15.             if (nums[mid] >= target) {
  16.                 r = mid;
  17.             } else {
  18.                 l = mid;
  19.             }
  20.         }
  21.         // 下表超尾或者下表的值不等于 target 就说明不存在
  22.         if (r >= nums.length || nums[r] != target) {
  23.             return -1;
  24.         }
  25.         return r;
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement