zoukankan      html  css  js  c++  java
  • LeetCode第34题

    常规二分

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            if(nums == null || nums.length < 1){
                return new int[]{-1,-1};
            }
            int[] res = new int[]{-1,-1};
            int len = nums.length;
            int left = 0;
            int right = len - 1;
            int mid = (left + right) >> 1;//寻找最小index时,不需要-1,因为右移会向下取整
            while(left < right){//找leftIndex
                if(nums[mid] < target){
                    left = mid + 1;
                }
                else if(nums[mid] > target){
                    right = mid - 1;
                }else{
                    right = mid;
                }
                mid = (left + right) >> 1;
            }
            if(nums[left] == target){
                res[0] = left;
            }
            right = len - 1;
            mid = ((left + right) >> 1) + 1;//因为要寻找最大的index,而右移会向下取整,所以需要+1,不进行+1,会出现死循环的情况
            while(left < right){//找rightIndex
                if(nums[mid] < target){
                    left = mid + 1;
                }
                else if(nums[mid] > target){
                    right = mid - 1;
                }else{
                    left = mid;
                }
                mid = ((left + right) >> 1) + 1;//一定要+1,这是易错点
            }
            if(nums[right] == target){
                res[1] = right;
            }
            return res;
        }
    }
  • 相关阅读:
    JAVA算术运算符
    java框架
    面向对象DAO模式
    JAVA JDK配置
    集合框架
    异常
    centos 部署 aspnetMVC 网页
    SQL四种语言:DDL,DML,DCL,TCL 的区别
    javascript download geoserver layer as kml file
    常用协议 —— hessian://
  • 原文地址:https://www.cnblogs.com/yu-xia-zheng-ye/p/14068714.html
Copyright © 2011-2022 走看看