题解 | #二分查找-I#
二分查找-I
https://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param target int整型 * @return int整型 */ public int search (int[] nums, int target) { // write code here if (nums == null){ return -1; } else if (nums.length == 0) { return -1; } int star = 0; int end = nums.length - 1; // 位移-只知道左边界右移多少就行了 while (true) { int i = (end - star) / 2; i += star; // 刚好就是 if (target == nums[i]) { return i; // 在右侧,左边界右移 } // 处理找不到的情况 1 2 3 5 7 8 else if (star >= end) { return -1; } else if (target > nums[i]) { star = i + 1; } else if (target < nums[i]) { // 在左侧,右边界左移 end = i - 1; } } } }