博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 702. Search in a Sorted Array of Unknown Size
阅读量:7068 次
发布时间:2019-06-28

本文共 1304 字,大约阅读时间需要 4 分钟。

Problem

Given an integer array sorted in ascending order, write a function to search target in nums. If target exists, then return its index, otherwise return -1. However, the array size is unknown to you. You may only access the array using an ArrayReader interface, where ArrayReader.get(k) returns the element of the array at index k (0-indexed).

You may assume all integers in the array are less than 10000, and if you access the array out of bounds, ArrayReader.get will return 2147483647.

Example 1:

Input: array = [-1,0,3,5,9,12], target = 9

Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:

Input: array = [-1,0,3,5,9,12], target = 2

Output: -1
Explanation: 2 does not exist in nums so return -1

Note:

You may assume that all elements in the array are unique.

The value of each element in the array will be in the range [-9999, 9999].

Solution

class Solution {    public int search(ArrayReader reader, int target) {        //find higher bound        int r = 1;        while (reader.get(r) < target) r *= 2;        //then you know lower bound        int l = r/2;        while (l <= r) {            int m = l+(r-l)/2;            if (reader.get(m) == target) return m;            else if (reader.get(m) < target) l = m+1;            else r = m-1;        }        return -1;    }}

转载地址:http://cghll.baihongyu.com/

你可能感兴趣的文章
“云+AI”,华为云使能互联网应用云基础设施创新
查看>>
数据库高可用性简史
查看>>
元宵节离家之前,帮爸妈安装这六个APP才是正经事
查看>>
甘肃敦煌社火“舞”出浓浓年味
查看>>
清者自清!国际泳联为孙杨“药检风波”盖棺定论
查看>>
巴西一大坝垮塌引发泥石流 铁路桥冲断桥身不见踪影
查看>>
韩国瑜:高雄从未这么重要“等了100年才变重心”
查看>>
学习Java的几个阶段,这样走你会学的更好!
查看>>
山西沁县推广生物质能清洁供暖 改造完成4000余户
查看>>
人民币对美元汇率中间价报6.7774元 下调109个基点
查看>>
施耐德电气本土专利“破千”原创战略成果初现
查看>>
热烈祝贺刘鹏教授膺选第45届世界技能大赛云计算赛事中国赛区裁判长!
查看>>
JavaScript是如何工作的:使用MutationObserver跟踪DOM的变化
查看>>
2017年5月iOS招人心得(附面试题)
查看>>
大白话说java并发工具类-Semaphore,Exchanger
查看>>
个推数据统计产品(个数)iOS集成实践
查看>>
在单页应用中,如何优雅的监听url的变化
查看>>
iOS笔记之Runtime
查看>>
基于 Module 的 Laravel API 架构
查看>>
Swift4 0新特性之String、Array和Dictionary
查看>>