当前位置:网站首页>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
边栏推荐
- 3 Month Tester Readme: 4 Important Skills That Impacted My Career
- 手写博客平台~第二天
- 哈希冲突和一致性哈希
- Shell Beginners Final Chapter
- LeetCode Review Diary: 34. Find the first and last position of an element in a sorted array
- 【轮式里程计】
- MySQL8 下载、启动、配置、验证
- Data transfer at the data link layer
- Hiring a WordPress Developer: 4 Practical Ways
- LeetCode brushing diary: 53, the largest sub-array and
猜你喜欢
随机推荐
密码学的基础:X.690和对应的BER CER DER编码
6-24漏洞利用-vnc密码破解
有效进行自动化测试,这几个软件测试工具一定要收藏好!!!
制造企业数字化转型现状分析
LeetCode Review Diary: 34. Find the first and last position of an element in a sorted array
LeetCode刷题日记:74. 搜索二维矩阵
Ask God to answer, how should this kind of sql be written?
Pcie the inbound and outbound
Force buckle, 752-open turntable lock
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
Two ways to pass feign exceptions: fallbackfactory and global processing Get server-side custom exceptions
Redis 订阅与 Redis Stream
求大神解答,这种 sql 应该怎么写?
canal realizes mysql data synchronization
飞桨开源社区季度报告来啦,你想知道的都在这里
A full set of common interview questions for software testing functional testing [open thinking questions] interview summary 4-3
Data transfer at the data link layer
手写一个博客平台~第三天
力扣、752-打开转盘锁
LeetCode刷题日记:LCP 03.机器人大冒险









