• 在排序数组中查找元素的第一个和最后一个位置


    解题:利用二分找到一个相等的元素,之后再左右边界

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int n=nums.length;
            int l=0,r=n-1;
            int start=-1,end=-1;
            while(l<=r){
                int mid=(r+l)/2;
                if(nums[mid]==target){
                    start=mid;
                    end=mid;
                    int temp=mid;
                    while(nums[mid]==target){
                         mid--;
                         if(mid==-1) break;
                    }
                    start=mid+1;
                    while(nums[temp]==target){
                        temp++;
                        if(temp==n) break;
                    } 
                    end=temp-1;
                    break;
                }else if(nums[mid]>target){
                    r=mid-1;
                }else{
                    l=mid+1;
                }
            }
            return new int[]{start,end};
    
        }
    }
    


    在找到一个一个等于target数时做两种不同的选择,r=mid-1,l=mid+1可以找出左右边界

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            return new int[]{binarySearchLeftBound(nums, target),binarySearchRightBound(nums, target)};
            
        }
        public int binarySearchLeftBound(int[] nums, int target) {
            int l = 0, r = nums.length - 1;
            while (l <= r) {
                int mid = l + ((r - l) >> 1);
                if (nums[mid] < target)  {
                    l = mid + 1;
                } else if (nums[mid] > target) {
                    r = mid - 1;
                } else if (nums[mid] == target) {
                    r = mid - 1;
                }
            }        
            if (l >= nums.length || nums[l] != target) return -1;
            return l;
        }
        public int binarySearchRightBound(int[] nums, int target) {
            int l = 0, r = nums.length - 1;
            while (l <= r) {
                int mid = l + ((r - l) >> 1);
                if (nums[mid] < target)  {
                    l = mid + 1;
                } else if (nums[mid] > target) {
                    r = mid - 1;
                } else if (nums[mid] == target) {
                    l = mid + 1;
                }
            }
            if (r < 0 || nums[r] != target) return -1;
            return r;
        }
    }
    
    
    不一样的烟火
  • 相关阅读:
    硬盘坏道及后续的拯救工作
    Extension GL_VERSION_1_2 could not be loaded.
    js显示当前的年月日时分秒
    如何删除桌面上的回收站?
    Fedora 15 U盘 安装心得
    庄子·内篇·逍遥游
    Additional Oracle Performance Extensions
    Features Specific to JDBC OCI Driver
    OracleDatabase 配置
    vim字符编码设置
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13328261.html
Copyright © 2020-2023  润新知