zoukankan      html  css  js  c++  java
  • 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]
    
    
    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int[] res = {-1,-1};
            int left = 0, right = nums.length - 1;
            int l = -1, r = -1;
            while(left <= right){
                int mid = left + (right-left)/2;
                if(nums[mid] == target){
                    l = mid;
                    r = mid;
                    while((l-1) > -1 && nums[l-1] == target){
                        l--;
                    }
                    while((r+1) < nums.length && nums[r+1] == target){
                        r++;
                    }
                    break;//!!
                }
                else{
                    if(nums[mid] > target){
                        right = mid - 1;
                    }
                    else left = mid + 1;
                }
            }
            res[0] = l;
            res[1] = r;
            return res;
        }
    }
    
    
    
     

    Binary Search。之所以要break是因为一旦所有符号条件的数选完就不会进入到下面的else,也不会更新right和left,所以会有time limit error。因此当得到l和r就应该break。

    总结:Using two pointers again, first is to use binary search to find the first target, then make l = mid and r = mid, expand in two directions and break. Then l is the first index, r is the last index. Including the situations that nums.length == 0/1 or only 1 target in array.

  • 相关阅读:
    Net包管理NuGet(3)搭建私服及引用私服的包
    MyMql 下载以及配置
    Oracle 环境部署 以及数据库创建 ,用户新建和权限分配
    VUE.JS 环境配置
    .NET WEB API 简单搭建
    C# Timer 定时任务
    RemoTing 搭建简单实现
    MVC+EF三层+抽象工厂
    ASP.NET MVC SignalR 简单聊天推送笔记
    .net Mvc Dapper 方法封装
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10332409.html
Copyright © 2011-2022 走看看