LintCode 61. Search for a Range 原创Java参考解答

LintCode 61. Search for a Range 原创Java参考解答

问题描述

http://www.lintcode.com/en/problem/search-for-a-range/

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

解题思路

题目是在一组可能有重复元素的已排序数组中,找到某个目标值的起始位置和结束位置。

两次二分法解决。第一次二分法查找目标值的起始位置,第二次二分法查找目标值的结束位置。

参考代码

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 firstPosition = -1; 
        int lastPosition = -1; 
        if (A == null || A.length == 0) { 
            return new int[]{firstPosition, lastPosition}; 
        } 
         
        // find first appearance 
        int start = 0; 
        int end = A.length - 1; 
         
        while (start + 1 < end) { 
            int mid = start + (end - start) / 2; 
            if (A[mid] == target) { 
                end = mid; 
            } else if (A[mid] > target) { 
                end = mid; 
            } else { 
                start = mid; 
            }         
        }         
         
        if (A[start] == target) { 
            firstPosition = lastPosition = start; 
        } else if (A[end] == target) { 
            firstPosition = lastPosition = end; 
        } else { 
            return new int[]{-1, -1}; 
        } 
 
        start = 0; 
        end = A.length - 1; 
         
        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) { 
            lastPosition = end; 
        } else if (A[start] == target) { 
            lastPosition = start; 
        }  
         
        return new int[]{firstPosition, lastPosition}; 
    } 
} 

相关题目

LintCode All in One 原创题目讲解汇总

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注