• lintcode61- Search for a Range- medium


    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].

    Challenge 

    O(log n) time.

    二分查找法找first 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) {
            // find the first
            int[] result = new int[2];
            for (int i = 0; i < result.length; i++){
                result[i] = -1;
            }
    
            if (A == null || A.length == 0){
                return result;
            }
    
            int start = 0;
            int end = A.length - 1;
            while (start + 1 < end){
                int mid = start + (end - start) / 2;
                if (target <= A[mid]){
                    end = mid;
                } else {
                    start = mid;
                }
            }
    
            // search forward
            if (A[start] == target){
                result[0] = start;
                result[1] = start;
                while (result[1] + 1 < A.length && A[result[1] + 1] == target){
                    result[1]++;
                }
            } else if (A[end] == target){
                result[0] = end;
                result[1] = end;
                while (result[1] + 1 < A.length && A[result[1] + 1] == target){
                    result[1]++;
                }
            }
            return result;
    
    
        }
    }
  • 相关阅读:
    P1983 车站分级
    P1807 最长路
    P1347 排序
    P1073 最优贸易 (tarjan缩点+dp)
    最小费用最大流解决KM匹配问题
    CF191C Fools and Roads
    case when
    防呆机制
    DbCommand :执行超时已过期。完成操作之前已超时或服务器未响应。
    存储过程带参数和sqlcommand
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7594807.html
Copyright © 2020-2023  润新知