小白筆記--------------------------leetcode 34. Search for a Range

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]


這道題參考了博文http://blog.csdn.net/linhuanmars/article/details/20593391

這篇文章講得很好,尤其是左右下標滑動找到結果的方式,很棒!

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int ll = 0;
        int lr = nums.length - 1;
        int rl = 0;
        int rr = nums.length - 1;
        
        int[] result = new int[2];
         result[0] = -1;
           result[1] = -1;
        
        int m1 = 0;
        int m2= 0;
        
        if(nums == null || nums.length == 0){
           return result;
        }
            
        while(ll <= lr){
            m1 = (ll + lr)/2;
            
            if(nums[m1] <  target){
                ll = m1 + 1;
            }else{
                lr = m1 -1;
            }
        }
        while(rl <= rr){
            m2 = (rl + rr)/2;
            if(nums[m2] <= target){
                rl = m2 +1;
            }else{
                rr = m2 -1;
            }
        }
        if(ll <= rr){
            result[0] = ll;
            result[1] = rr;
        }
        
        return result;
    }
}



發佈了102 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章