Lintcode阶梯训练~算法

搜索区间

2017-06-28  本文已影响12人  lyoungzzz

描述

给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]

样例

给出[5, 7, 7, 8, 8, 10]和目标值 target=8,
返回[3, 4]
给出[1]和目标值target=1,
返回[0,0]

相关题目

目标出现次数总和

代码实现

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[] result = new int[2];
        if (A == null || A.length == 0) {
            result[0] = -1;
            result[1] = -1;
            return result;
        }
        if (A.length == 1 && A[0] == target) {
            result[0] = 0;
            result[1] = 0;
            return result;
        }
        int start = 0;
        int end = A.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] < target) {
                start = mid;
            } else  {
                end = mid;
            } 
        }
        if (A[start] == target) {
            result[0] = start;
            for (int i = A.length-1; i >= start; i--) {
                if (A[i] == target) {
                    result[1] = i;
                    return result;
                }
            }
            result[1] = start;
            return result;
        }
        else if (A[end] == target) {
            result[0] = end;
            for (int i = A.length-1; i >= end; i--) {
                if (A[i] == target) {
                    result[1] = i;
                    return result;
                }
            }
            result[1] = end;
            return result;
        } else {
            result[0] = -1;
            result[1] = -1;
            return result;
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读