Problem

Given a sorted array of n integers, find the starting and ending position of a given target value.

If the target is not found in the array, return [-1, -1].

Example
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

思路

  1. 暴力解法, 一边for循环
  2. 优化, 二分法 找到第一个target 和最后一个target
    public int[] searchRange(int[] A, int target) {
        int[] results = {-1, -1};
        if (A == null || A.length == 0) {
            return results;
        }

        int start = 0;
        int end = A.length - 1;

        // find the first target element 
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] < target) {
                start = mid;
            } else if (A[mid] > target) {
                end = mid;
            } else {
                end = mid;
            }
        }
        if (A[start] == target) {
            results[0] = start;
        } else if (A[end] == target) {
            results[0] = end;
        } else {
            results[0] = -1;
        }

        start = 0;
        end = A.length - 1;

        // find the last target element
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] < target) {
                start = mid;
            } else if (A[mid] > target) {
                end = mid;
            } else {
                start = mid;
            }
        }
        if (A[end] == target) {
            results[1] = end;
        } else if (A[start] == target) {
            results[1] = start;
        } else {
            results[1] = -1;
        }

        return results;
    }

results matching ""

    No results matching ""