算法系列——Search for a Range

来源:互联网 发布:cnc编程上班时间是怎样 编辑:程序博客网 时间:2024/05/23 02:00

题目描述

Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

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

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

解题思路

这个题目涉及到二分查找。需要找到指定元素的第一个位置,和最后出现的位置,我们需要实现两次二分查找。时间复杂度为O(logn).

注意边界值的取值。关于二分查找法的总结请参考此篇连接

http://www.cnblogs.com/bofengyu/p/6761389.html

程序实现

public class Solution {    public int[] searchRange(int[] nums, int target) {         int[] result={-1,-1};         if(nums==null||nums.length==0)             return result;        result[0]=findFirstIndex(nums,target);        result[1]=findLastIndex(nums,target);        return result;    }    private int findFirstIndex(int []nums,int target){        int left=0,right=nums.length-1;        while(left<=right){            int mid=(left+right)/2;            if(target<=nums[mid])                right=mid-1;            else                left=mid+1;        }        if(left>=0&&left<=(nums.length-1)&&nums[left]==target)            return left;        return -1;    }    private int findLastIndex(int []nums,int target){         int left=0,right=nums.length-1;        while(left<=right){            int mid=(left+right)/2;            if(target<nums[mid])                right=mid-1;            else                left=mid+1;        }        if(right>=0&&right<=(nums.length-1)&&nums[right]==target)            return right;        return -1;    }}
原创粉丝点击