LintCode 61. 搜索区间

给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。

如果目标值不在数组中,则返回[-1, -1]

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) {
      // write your code here
      if (A == null || A.length == 0) {
         int[] tmp = {-1, -1};
         return tmp;
      }
      return search(A, 0, A.length - 1, target);
   }

   private int[] search(int[] A, int start, int end, int target) {
      if (start == end) {
         if (A[start] == target) {
            int[] tmp = {start, end};
            return tmp;
         } else {
            int[] tmp = {-1, -1};
            return tmp;
         }
      }
      int middle = (start + end) / 2;
      int[] left = search(A, start, middle, target);
      int[] right = search(A, middle + 1, end, target);
      if (left[0] == -1) {
         return right;
      } else if (right[0] == -1) {
         return left;
      } else {
         int[] tmp = {left[0], right[1]};
         return tmp;
      }
   }
}


阅读更多

没有更多推荐了,返回首页