小白笔记--------------------------leetcode 34. Search for a Range

来源:互联网 发布:初学室内设计的软件 编辑:程序博客网 时间:2024/06/06 12:56

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;    }}



原创粉丝点击