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 l = 0, r = nums.length - 1;
            if (nums.length == 0) return new int[]{-1, -1};
            while (l < r) {
                int mid = (l + r) >> 1;
                if (nums[mid] >= target) {
                    r = mid;
                } else {
                    l = mid + 1;
                }
            }
            
            int []ans = new int[2];
            if (nums[l] == target)
                ans[0] = l;
            else 
                ans[0] = -1;
            
            System.out.println(ans[0]);
            l = 0;
            r = nums.length - 1;
            while (l < r) {
                int mid = (l + r) >> 1;
                if (nums[mid] <= target) {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            }
            if (r < nums.length && r >= 0 && nums[r] == target) {
                ans[1] = r;
            } else if (r - 1 >= 0 && nums[r - 1] == target) {
                ans[1] = r - 1;
            } else
                ans[1] = -1;
            
            return ans;
        }
    }
  • 相关阅读:
    中断解析
    中断分类
    中断分类
    在iOS开发中使用FMDB
    大数据权限授权管理框架:Apache Sentry和Ranger
    Flink FileSystem的connector分析
    Flink FileSystem的connector分析
    Flink JobManager的HA原理分析
    Flink JobManager的HA原理分析
    Flink的State概述
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12310151.html
Copyright © 2011-2022 走看看