码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: 34. Search for a Range

时间:2016-08-11 13:02:21      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

Given a sorted array of integers, 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].

 

题目大意:给一个排序后的数组,和一个target value,找到这个数字在数组中的开始位置和结束位置(可能有多个),如果没有找到target,返回-1,-1

复杂度必须为logN级

 

思路:logn必为二分查找,找到第一个等于target的element,向左和向右找到range的起始

 

算法构架:增加一个二分查找函数,返回找到的第一个等于target的element的位置,然后从当前位置向前和向后找到边界

 

public class Solution 
{
    public int[] searchRange(int[] nums, int target) 
    {
        int[] res = new int[] {-1,-1};
        
        if (nums == null || nums.length == 0)
        {
            return res;
        }
        
        int start = binarySearch(nums, target);
        int temp = start;
        
        if (start == -1)
        {
            return res;
        }
        
        while (temp >= 0 && nums[temp] == target)
        {
            temp--;
        }
        res[0] = temp+1;
        temp = start;
        while (temp < nums.length && nums[temp] == target)
        {
            temp++;
        }
        res[1] = temp-1;
        
        return res;
    }
    
    private int binarySearch(int[] nums, int target)
    {
        int left = 0;
        int right = nums.length-1;
        
        while (left <= right)
        {
            int mid = left + (right-left) / 2;
            
            if (nums[mid] == target)
            {
                return mid;
            }
            else if (nums[mid] > target)
            {
                right = mid-1;
            }
            else
            {
                left = mid+1;
            }
        }
        
        return -1;
    }
}

 

LeetCode: 34. Search for a Range

标签:

原文地址:http://www.cnblogs.com/snakech/p/5760476.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!