一起合伙做项目的网站,深圳网站建设小江,博罗网站开发,平台公司属于什么行业文章目录1. 题目2. 解题1. 题目
给定一个升序整数数组#xff0c;写一个函数搜索 nums 中数字 target。 如果 target 存在#xff0c;返回它的下标#xff0c;否则返回 -1。注意#xff0c;这个数组的大小是未知的。 你只可以通过 ArrayReader 接口访问这个数组#xff0…
文章目录1. 题目2. 解题1. 题目
给定一个升序整数数组写一个函数搜索 nums 中数字 target。 如果 target 存在返回它的下标否则返回 -1。注意这个数组的大小是未知的。 你只可以通过 ArrayReader 接口访问这个数组ArrayReader.get(k) 返回数组中第 k 个元素下标从 0 开始。
你可以认为数组中所有的整数都小于 10000。 如果你访问数组越界ArrayReader.get 会返回 2147483647。
样例 1
输入: array [-1,0,3,5,9,12], target 9
输出: 4
解释: 9 存在在 nums 中下标为 4样例 2
输入: array [-1,0,3,5,9,12], target 2
输出: -1
解释: 2 不在数组中所以返回 -1注释
你可以认为数组中所有元素的值互不相同。
数组元素的值域是 [-9999, 9999]。来源力扣LeetCode 链接https://leetcode-cn.com/problems/search-in-a-sorted-array-of-unknown-size 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。 2. 解题
/*** // This is the ArrayReaders API interface.* // You should not implement it, or speculate about its implementation* class ArrayReader {* public:* int get(int index);* };*/class Solution {
public:int search(const ArrayReader reader, int target) {if(target10000 || target -10000)return -1;int l 0, r INT_MAX, mid, val;while(l r){mid l((r-l)1);val reader.get(mid);if(val target)r mid-1;else if(val target)l mid1;elsereturn mid;}return -1;}
};44 ms 10.1 MB 长按或扫码关注我的公众号一起加油、一起学习进步