1.基础版
public int search(int[] nums, int target) { int i = 0, j = nums.length - 1; while (i <= j) { int middle = (i + j) >>> 1; if (target < nums[middle]) { j = middle - 1; } else if (target > nums[middle]) { i = middle + 1; } else { return middle; } } return -1; }
2.改动版
public int search(int[] nums, int target) { int i = 0, j = nums.length; while (i < j) { int middle = (i + j) >>> 1; if (target < nums[middle]) { j = middle; } else if (target > nums[middle]) { i = middle + 1; } else { return middle; } } return -1; }
3.平衡版
public int search(int[] nums, int target) { int i = 0, j = nums.length; while (i + 1 < j) { int middle = (i + j) >>> 1; if (target < nums[middle]) { j = middle; } else { i = middle; } } return nums[i] == target ? i : -1;
}
标签:二分,return,target,nums,int,else,middle,查找 From: https://www.cnblogs.com/gstszbc/p/18383387