zoukankan      html  css  js  c++  java
  • LeetCode-34.Find First and Last Position of Element in Sorted Array

    Given an array of integers nums 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].

    Example 1:

    Input: nums = [5,7,7,8,8,10], target = 8
    Output: [3,4]

    Example 2:

    Input: nums = [5,7,7,8,8,10], target = 6
    Output: [-1,-1]

    二分查找的变形 ,时间复杂度O(lgn)

        public int[] searchRange(int[] nums, int target) {//二分 my
            int[] re = new int[2];
            re[0] = bSearchFirst(nums,target);
            re[1] = bSearchLast(nums,target);
            return re;
        }
        
        private int bSearchFirst(int[] nums,int target){
            if(null==nums||0==nums.length){
                return -1;
            }
            int left = 0;
            int right = nums.length-1;
            while(left<= right){
                int mid = (left+right)/2;
                if(nums[mid] >target){
                    right = mid-1;
                }
                else if(nums[mid]<target) {
                    left = mid+1;
                }
                else if((mid==0)||(nums[mid-1]!=target)){//如果nums[mid]=target,而且是第一个
                        return mid;
                }
                else{//如果nums[mid]=target,而且不是第一个
                    right = mid-1;
                } 
            }
            return -1;
        }
        private int bSearchLast(int[] nums,int target){
            if(null==nums||0==nums.length){
                return -1;
            }
            int left = 0;
            int right = nums.length-1;
            while(left<= right){
                int mid = (left+right)/2;
                if(nums[mid] >target){
                    right = mid-1;
                }
                else if(nums[mid]<target){
                    left = mid+1;
                }
                else if((mid==nums.length-1)||(nums[mid+1]!=target)){//如果nums[mid]=target,而且是最后一个
                        return mid;
                }
                else {//如果nums[mid]=target,而且是最后一个
                    left = mid+1;
                }
            }
            return -1;
        }
  • 相关阅读:
    21.网络文件共享服务
    20.LANMP架构
    18.自动运维工具ansible
    17.MySQL数据库
    16.DNS服务
    15.系统自动部署
    14.加密技术和安全
    13.系统启动和服务管理
    12.进程管理和计划任务
    11.网络管理和配置
  • 原文地址:https://www.cnblogs.com/zhacai/p/11023279.html
Copyright © 2011-2022 走看看