zoukankan      html  css  js  c++  java
  • Search for a Range

    binary search

     1 public class Solution {
     2     public int[] searchRange(int[] A, int target) {
     3         // IMPORTANT: Please reset any member data you declared, as
     4         // the same Solution instance will be reused for each test case.
     5         int[] result = new int[2];
     6         if(A == null){
     7             result[0] = -1;
     8             result[1] = -1;
     9             return result;
    10         }
    11         
    12         
    13         int start = search(A, ((double)target)-0.5, 0, A.length);
    14         int end = search(A, ((double)target)+0.5, 0, A.length);
    15         if(start == end){
    16             result[0] = -1;
    17             result[1] = -1;
    18             return result;
    19         }
    20         else{
    21             result[0] = start;
    22             result[1] = end - 1;
    23             return result;
    24         }
    25     }
    26     
    27     private int search(int[] A, double target, int start, int end){
    28         if(start >= end)
    29             return start;
    30         int mid = (start + end) / 2;
    31         if(target == A[mid])
    32             return mid;
    33         else if(target < A[mid])
    34             return search(A, target, start, mid);
    35         else
    36             return search(A, target, mid+1, end);
    37     }
    38 }
  • 相关阅读:
    Linux如何修改命令提示符
    Linux命令详解-install
    Linux命令详解-info
    Linux命令详解-man
    Linux命令详解-printf
    Linux命令详解-echo
    Linux命令详解-whatis
    Linux命令详解-file
    Linux命令详解-help
    Linux命令详解-type
  • 原文地址:https://www.cnblogs.com/jasonC/p/3430593.html
Copyright © 2011-2022 走看看