import java.util.*; public class Solution { public int search (int[] nums, int target) { int l = 0; int r = nums.length - 1; //从数组首尾开始,直到二者相遇 fast-template while(l <= r){ //每次检查中点的值 int m = (l + r) / 2; if(nums[m] == target) return m; //进入左的区间 if(nums[m] > target) r = m - 1; //进入右区间 else l = m + 1; } //未找到 return -1; } }
优化
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param target int整型 * @return int整型 */ public int search (int[] nums, int target) { // write code here int left=0; int right=nums.length-1; while(left<=right){ int mid=left+((right-left)>>1);//防止相加超出int范围 if(nums[mid]==target){ return mid; }else if(target<nums[mid]){ right=mid-1; }else{ left=mid+1; } } return -1; } }