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

Jan 16 - Search for a Range; Array; Binary Search;

时间:2016-01-17 06:29:48      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

注意index不要出现out of bounds的情况:

代码:

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int len = nums.length;
        int high = len-1;
        int low = 0;
        int index1 = -1, index2 = -1;
        int[] result = new int[2];
        result[0] = index1;
        result[1] = index2;
        while(low <= high){
            int mid = (high+low)/2;
            int mid_num = nums[(high+low)/2];
            if(mid_num < target) low = mid+1;
            else if(mid_num > target) high = mid-1;
            else{
                index1 = index2 = mid;
                while(index1 >= 1 && nums[index1-1] == mid_num) index1--;
                while(index2 < len-1 && nums[index2+1] == mid_num) index2++;
                result[0] = index1; 
                result[1] = index2;
                return result;
            }
        }
        return result;
        
        
    }
}

  

Jan 16 - Search for a Range; Array; Binary Search;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5136735.html

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