Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Given an array of integers nums which is sorted in ascending order,
- // and an integer target, write a function to search target in nums.
- // If target exists, then return its index. Otherwise, return -1.
- //
- //You must write an algorithm with O(log n) runtime complexity
- public class Solution {
- public int search(int[] nums, int target) {
- int l = -1;
- int r = nums.length;
- int mid;
- // 二分查找大于等于 target 值的最小下标
- while (r - l > 1) {
- mid = (l + r) / 2;
- if (nums[mid] >= target) {
- r = mid;
- } else {
- l = mid;
- }
- }
- // 下表超尾或者下表的值不等于 target 就说明不存在
- if (r >= nums.length || nums[r] != target) {
- return -1;
- }
- return r;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement