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

Search for a Range

时间:2014-06-15 16:53:32      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:array   leetcode   java   二分查找   

题目

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

方法

使用二分查找,找到之后左右移动,获取边界。
    public int[] searchRange(int[] A, int target) {
        int len = A.length;
        int left = 0;
        int right = len - 1;
        

        int flag = -1;
        while (left <= right) {
        	
            int median = left + (right - left) / 2;
            if (A[median] == target) {
            	flag = median;
            	break;
            } else if (A[median] > target) {
                right = median - 1;
            } else {
                left = median + 1;
            }
        }
        int[] result;
        if (flag != -1) {
            int leftIndex = flag;
            int rightIndex = flag;
            while (rightIndex < len) {
            	if (A[rightIndex] == target) {
            		rightIndex++;
            	} else {
            		break;
            	}            	
            }
            while (leftIndex >= 0) {
            	if (A[leftIndex] == target) {
            		leftIndex--;
            	} else {
            		break;
            	}
            	
            }
            result = new int[]{leftIndex + 1, rightIndex - 1};
        } else {
            result = new int[]{-1, -1};
        }
        return result;
    }


Search for a Range,布布扣,bubuko.com

Search for a Range

标签:array   leetcode   java   二分查找   

原文地址:http://blog.csdn.net/u010378705/article/details/30483569

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