zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Java图片裁剪
    jvm参数
    Druid数据源监控配置
    执行jar包或执行其中的某个类
    十进制和二进制之间的相互转化
    Java位运算
    获取网络资源保存本地
    前端PHP入门-010-内部函数
    前端PHP入门-011-可变函数
    前端PHP入门-009-匿名函数
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4890857.html
Copyright © 2011-2022 走看看