zoukankan      html  css  js  c++  java
  • [Algo] 20. Search In Unknown Sized Sorted Array

    Given a integer dictionary A of unknown size, where the numbers in the dictionary are sorted in ascending order, determine if a given target integer T is in the dictionary. Return the index of T in A, return -1 if T is not in A.

    Assumptions

    • dictionary A is not null
    • dictionary.get(i) will return null(Java)/INT_MIN(C++)/None(Python) if index i is out of bounds

    Examples

    • A = {1, 2, 5, 9, ......}, T = 5, return 2
    • A = {1, 2, 5, 9, 12, ......}, T = 7, return -1
    /*
    *  interface Dictionary {
    *    public Integer get(int index);
    *  }
    */
    
    // You do not need to implement the Dictionary interface.
    // You can use it directly, the implementation is provided when testing your solution.
    public class Solution {
      public int search(Dictionary dict, int target) {
        // Write your solution here
        int start = 0;
        int end = 1;
        while (dict.get(end) != null && dict.get(end) <= target) {
          start = end;
          end = 2 * end;
        }
    
        while (start <= end) {
          int mid = start + (end - start) / 2;
          if (dict.get(mid) == null || dict.get(mid) > target) {
            end = mid - 1;
          } else if (dict.get(mid) < target) {
            start = mid + 1;
          } else {
            return mid;
          }
        }
        return -1;
      }
    }
  • 相关阅读:
    arm基础
    数据的封装
    网络安全基础
    qt5学习笔记
    nginx修改配置
    proteus_base1
    20191022
    20191015
    20191014
    20191013
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12776598.html
Copyright © 2011-2022 走看看