• 二分查找向左或向右紧缩


     class Solution {
         public int[] searchRange(int[] nums, int target) {
       int[] res=new int[2];
          
                      res[0]=findleft(nums,target);
                      res[1]=findright(nums,target);
                      return res;
         }
         private int findright(int[] nums, int target) {
          int left=0;
          int right=nums.length;   //向左或向右紧缩时,就用nums.length; 因此while里为<号 不带等号 等就越界
          while (left<right) {
         int mid=(left+right)>>1;
          if (nums[mid]==target) {
           left=mid+1;    //向右,因为是right=nums.length;所以是左闭右开
          }
          else if (nums[mid]<target) {
           left=mid+1;
          }
          else {
           right=mid;
          }
        }
         if (left == 0) return -1;    //向右紧缩  却缩到了最左侧 说明没找到
                    return nums[left-1] == target ? (left-1) : -1;
       }

       private int findleft(int[] nums, int target) {
         int left=0;
          int right=nums.length;
          while (left<right) {
         int mid=(left+right)>>1;
          if (nums[mid]==target) {
           right=mid;      //向左紧缩,因为是right=nums.length;所以是左闭右开
          }
          else if (nums[mid]<target) {
           left=mid+1;
          }
          else {
           right=mid;
          }
        }
       if (left >= nums.length || nums[left] != target)//向左紧缩,却缩到了最右侧 说明没找到
                          return -1;
               return left;
       }
     }
  • 相关阅读:
    o gdb
    net -t struct ifreq
    file -x stat()-fstat()-lstat()
    I/O -x fcntl()
    I/O -x dup() dup2()
    14条---注意点
    user -x userid
    err -x perror() strerror()
    苹果电脑挂载NTFS移动硬盘
    ASP.NET Core之EF Core学习笔记
  • 原文地址:https://www.cnblogs.com/wl889490/p/12608518.html
Copyright © 2020-2023  润新知