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.

  • 相关阅读:
    程序员励志语录
    javaEE的十一种技术
    gui内函数调用顺序
    m文件中函数的执行顺序
    VC++与Matlab混合编程之引擎操作详解(6)数据类型mxArray的操作
    GUI(2)
    时间管理
    Matlab GUI界面
    matlab GUI(2)
    MATLAB GUI平台
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10332409.html
Copyright © 2011-2022 走看看