classSolution {publicintsearch(int[] nums,int target) {// 目标值的下标int index =0;// 左右边界int left =0;int right =nums.length-1;// 注意是小于等于while (left <= right) { index = left + (right - left) /2;if (nums[index] == target)return index;elseif (nums[index] > target) right = index -1;else left = index +1; }// 没找到return-1; }}
3.2 Kotlin
classSolution {funsearch(nums: IntArray, target: Int): Int {// 目标值的下标var index =0// 左右边界var left =0var right = nums.size -1// 注意是小于等于while (left <= right) { index = left + (right - left) /2if (nums[index] == target)return indexelseif (nums[index] > target) right = index -1else left = index +1 }// 没找到return-1 }}