标签:
注意index不要出现out of bounds的情况:
代码:
public class Solution { public int[] searchRange(int[] nums, int target) { int len = nums.length; int high = len-1; int low = 0; int index1 = -1, index2 = -1; int[] result = new int[2]; result[0] = index1; result[1] = index2; while(low <= high){ int mid = (high+low)/2; int mid_num = nums[(high+low)/2]; if(mid_num < target) low = mid+1; else if(mid_num > target) high = mid-1; else{ index1 = index2 = mid; while(index1 >= 1 && nums[index1-1] == mid_num) index1--; while(index2 < len-1 && nums[index2+1] == mid_num) index2++; result[0] = index1; result[1] = index2; return result; } } return result; } }
Jan 16 - Search for a Range; Array; Binary Search;
标签:
原文地址:http://www.cnblogs.com/5683yue/p/5136735.html