zoukankan      html  css  js  c++  java
  • [leedcode 34] Search for a Range

    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 class Solution {
        public int[] searchRange(int[] nums, int target) {
            //本题是在已排序的数组中进行查找,因此应用二分查找的思想
            //牢记二分查找的参数以及函数!
            //当找到target数时,进行顺序查找,设置两个指针,一个是left,代表最侧不为target的下标。另一个是right,代表最右侧不为target的下标
            //注意int 数组的初始化!int a[]={-1,-1};
            int[] result={-1,-1};
            if(nums.length<1) return result;
            int res=find(nums,target,0,nums.length-1);
            if(res==-1){
                return result;
                
            }
            int left=res-1;
            int right=res+1;
            while(left>=0&&nums[left]==target){
                     left--;
            }
             while(right<nums.length&&nums[right]==target){
                     right++;
            }
            int rel[]={left+1,right-1};
            return rel;
        }
        public int find(int[] nums,int target,int start,int end){
            if(start>end) return -1;
            int mid=(start+end)/2;
            if(nums[mid]==target){
                return mid;
            }
            if(target>nums[mid]){
                return find(nums,target,mid+1,end);
            }else{
                return find(nums,target,start,mid-1);
            }
        }
    }
  • 相关阅读:
    requests模块
    unitest模块
    doctest模块
    SessionStorage
    jquery选择器
    jquery操作dom
    jquery事件
    jquery筛选
    页面跳转传值接收
    HTML5 Web SQL 数据库操作
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4633904.html
Copyright © 2011-2022 走看看