Binary Search模板: mid 和 target 指针比较,left/ right 和 target 比较。
循环终止条件: 最后剩两数比较(while(left + 1 < right))。
循环结束后根据要求检查最后两个数(left/ right 和 target 比较)。
public class Solution { /** *@param A : an integer sorted array *@param target : an integer to be inserted *return : a list of length 2, [index1, index2] */ public int[] searchRange(int[] A, int target) { int[] array = new int[2]; array[0] = -1; array[1] = -1; if(A == null || A.length == 0) return array; int left = 0; int right = A.length - 1; while(left + 1 < right){ int mid = (left + right) / 2; if(A[mid] == target){ right = mid; } else if(A[mid] < target){ left = mid; } else if(A[mid] > target){ right = mid; } } if(A[left] == target){ array[0] = left; } else if(A[right] == target){ array[0] = right; } else array[0] = -1; left = 0; right = A.length - 1; while(left + 1 < right){ int mid = (left + right) / 2; if(A[mid] == target){ left = mid; } else if(A[mid] < target){ left = mid; } else if(A[mid] > target){ right = mid; } } if(A[right] == target){ array[1] = right; } else if(A[left] == target){ array[1] = left; } else array[1] = -1; return array; } }
时间: 2024-11-11 18:52:45