binary search模板:
1 class Solution { 2 /** 3 * @param nums: The integer array. 4 * @param target: Target to find. 5 * @return: The first position of target. Position starts from 0. 6 */ 7 public int binarySearch(int[] nums, int target) { 8 if (nums == null || nums.length == 0) { 9 return -1; 10 } 11 12 int start = 0, end = nums.length - 1; 13 while (start + 1 < end) { 14 int mid = start + (end - start) / 2; 15 if (nums[mid] == target) { 16 end = mid; 17 } else if (nums[mid] < target) { 18 start = mid; 19 } else { 20 end = mid; 21 } 22 } 23 if (nums[start] == target) { 24 return start; 25 } 26 if (nums[end] == target) { 27 return end; 28 } 29 return -1; 30 } 31 }