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

    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].

    *译:给定按升序排序的整数数组,找到给定目标值的起始位置和结束位置。 算法的运行时复杂度必须为O(log n)。 如果在数组中找不到目标,则返回[-1,-1]。 *

    梳理下解决方法

    • 直接遍历,用两个变量记录起始和结束为止,算法复杂度为0(n)。
    • 采用二分查找法找到其中一个等于目标值的数据,然后再左右扩展,复杂度为O(log n)。在最坏情况下(如:数组的值全为目标值),算法复杂度为O(n)。
    • 以上两种方式都不行,因为时间复杂度不满足,那么我们考虑是否有一种方式,直接能查找到最左边的等于目标函数的值,再次二分查找最右边的值,这样复杂度恰好为O(log n)。

    代码如下:

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            if (nums == null || nums.length == 0){
                return new int[]{-1, -1};
            }
    
            int left = 0, right = nums.length - 1;
            int[] res = new int[2];
            //找左边
            res[0] = binarySearchLowerBound(nums,target,left,right);
    
            //找右边
            res[1] = binarySearchUpperBound(nums, target, left, right);
    
            return res;
        }
    
        public int binarySearchLowerBound(int[] ints, int target,int low, int high){
            while(low <= high){
                int mid = low + (high - low) / 2;
                if(target <= ints[mid]){
                    high = mid - 1;
                }else{
                    low = mid + 1;
                }
            }
            if(low < ints.length && ints[low] == target)
                return low;
            else
                return -1;
        }
    
        public int binarySearchUpperBound(int[] ints, int target,int low, int high){
            while(low <= high){
                int mid = low + (high - low) / 2;
                if(target >= ints[mid]){
                    low = mid + 1;
                }else{
                    high = mid - 1;
                }
            }
            if(high >= 0 && ints[high] == target)
                return high;
            else
                return -1;
        }
    }
  • 相关阅读:
    嵌入式成长轨迹36 【Zigbee项目】【单片机基础】【单片机SD卡】
    嵌入式成长轨迹31 【嵌入式学习阶段】【ARM环境调试】【UbuntuWin7 NAT联网】
    一个jQuery弹出层(tipsWindown)
    sql的left join 命令详解
    input javascript 之 onclick 大全
    php中调用用户自定义函数的方
    asp 正则表达式使用方法
    conn.execute的用法
    vbscript中的True和False
    JavaScript Cookie 的正确用法
  • 原文地址:https://www.cnblogs.com/hirampeng/p/10891482.html
Copyright © 2011-2022 走看看