/** * 当查找到满足条件的值且是从左到右第一个的时候,right=mid-1,继续二分查找, * 会一直从left查找到nums[mid]=target的mid, * 1-----2 ---> 1-----2 ---> 1-----2 ---> 不满足条件返回a * a(mid) b ab(mid) b a * * @param nums * @param target * @return */ public static int search1(int[] nums, int target) { if (nums == null || nums.length == 0) { return -1; } int a = 0; int b = nums.length - 1; while (a <= b) { int mid = (a + b) / 2; if (nums[mid] > target) { b = mid - 1; } else if (nums[mid] < target) { a = mid + 1; } else { b = mid - 1; } } if (a >= nums.length || nums[a] != target) { return -1; } return a; }