当前位置:网站首页>LeetCode brushing diary: 33. Search and rotate sorted array
LeetCode brushing diary: 33. Search and rotate sorted array
2022-08-02 01:55:00 【light [email protected]】
整数数组 nums 按升序排列,数组中的值 互不相同 .
在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]](下标 从 0 开始 计数).例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] .
给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回 -1 .
你必须设计一个时间复杂度为 O(log n) 的算法解决此问题.
示例 1:
输入:nums = [4,5,6,7,0,1,2], target = 0
输出:4
示例 2:
输入:nums = [4,5,6,7,0,1,2], target = 3
输出:-1
示例 3:
输入:nums = [1], target = 0
输出:-1
提示:
1 <= nums.length <= 5000
-104 <= nums[i] <= 104
nums 中的每个值都 独一无二
题目数据保证 nums 在预先未知的某个下标上进行了旋转
-104 <= target <= 104
题解:
public static int search(int[] nums, int target) {
int res = -1;
int start = 0, end = nums.length-1;
if(nums.length == 0){
return -1;
}
if(nums.length == 1){
return nums[0] == target ? 0 : -1;
}
while (start <= end) {
int mid = (start + end)/2;
if(nums[mid] == target){
res = mid;
break;
}
// centering on the midpoint,添加多一个判断,
if(nums[mid] >= nums[start]){
if(nums[start] <= target && target < nums[mid] ){
end = mid-1;
}else{
start = mid + 1;
}
}else if(nums[mid] < nums[start]){
if(nums[mid] < target && target <= nums[nums.length-1]){
start = mid + 1;
}else{
end = mid - 1;
}
}
}
return res;
}
版权声明
本文为[light [email protected]~no trace]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208020144011690.html
边栏推荐
猜你喜欢

数据链路层的数据传输

『网易实习』周记(二)

Constructor instance method inheritance of typescript37-class (extends)

力扣 1161. 最大层内元素和

Constructor instance method of typescript36-class

typescript32-ts中的typeof

AOF重写

HSDC is related to Independent Spanning Tree

Huawei's 5-year female test engineer resigns: what a painful realization...

第一次写对牛客的编程面试题:输入一个字符串,返回该字符串出现最多的字母
随机推荐
Understand the big model in seconds | 3 steps to get AI to write a summary
Huawei's 5-year female test engineer resigns: what a painful realization...
三本毕业的我被腾讯拒绝了十四次,最终成功入职阿里
HSDC和独立生成树相关
HSDC is related to Independent Spanning Tree
信息化和数字化的本质区别是什么?
Day116.尚医通:预约挂号详情 ※
『网易实习』周记(二)
【刷题篇】打家劫舍
Two ways to pass feign exceptions: fallbackfactory and global processing Get server-side custom exceptions
Constructor of typescript35-class
Ask God to answer, how should this kind of sql be written?
Detailed explanation of fastjson
hash table
typescript34-class的基本使用
LeetCode刷题日记:LCP 03.机器人大冒险
安全(1)
Win Go开发包安装配置、GoLand配置
外包干了三年,废了...
A full set of common interview questions for software testing functional testing [open thinking questions] interview summary 4-3