• Search for a Range 解答


    Question

    Given a sorted array of integers, 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].

    For example,
    Given [5, 7, 7, 8, 8, 10] and target value 8,
    return [3, 4].

    Solution

    Use binary search, first, find left position, then, find right position.

     1 public class Solution {
     2     public int[] searchRange(int[] nums, int target) {
     3         int[] result = new int[2];
     4         result[0] = -1;
     5         result[1] = -1;
     6         if (nums == null || nums.length < 1)
     7             return result;
     8         int start = 0, end = nums.length - 1, mid, first, last;
     9         // Find first position of target
    10         while (start + 1 < end) {
    11             mid = (end - start) / 2 + start;
    12             if (nums[mid] >= target)
    13                 end = mid;
    14             else
    15                 start = mid;
    16         }
    17         if (nums[start] == target)
    18             result[0] = start;
    19         else if (nums[end] == target)
    20             result[0] = end;
    21         
    22         // Find last position of target
    23         start = 0;
    24         end = nums.length - 1;
    25         while (start + 1 < end) {
    26             mid = (end - start) / 2 + start;
    27             if (nums[mid] <= target)
    28                 start = mid;
    29             else
    30                 end = mid;
    31         }
    32         if (nums[end] == target)
    33             result[1] = end;
    34         else if (nums[start] == target)
    35             result[1] = start;
    36         return result;
    37     }
    38 }
  • 相关阅读:
    linux 操作系统 基础
    [HAOI2011]Problem A
    [HNOI2015] 菜肴制作
    [P3676]小清新数据结构题
    [NOI2016]区间
    [BOI2007]Mokia 摩基亚
    [NOI2012]美食节
    [CQOI2015]网络吞吐量
    [六省联考2017]期末考试
    [HNOI2015]亚瑟王
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4890857.html
Copyright © 2020-2023  润新知