当前位置:网站首页>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个月测试员自述:4个影响我职业生涯的重要技能
- Coding Experience Talk
- 雇用WordPress开发人员:4个实用的方法
- Rust P2P网络应用实战-1 P2P网络核心概念及Ping程序
- 【ORB_SLAM2】void Frame::AssignFeaturesToGrid()
- LeetCode刷题日记:LCP 03.机器人大冒险
- The ultra-large-scale industrial practical semantic segmentation dataset PSSL and pre-training model are open source!
- 『网易实习』周记(一)
- 飞桨助力航天宏图PIE-Engine地球科学引擎构建
- 密码学的基础:X.690和对应的BER CER DER编码
猜你喜欢
随机推荐
雇用WordPress开发人员:4个实用的方法
三本毕业的我被腾讯拒绝了十四次,最终成功入职阿里
Two ways to pass feign exceptions: fallbackfactory and global processing Get server-side custom exceptions
When paying attention to the "Internet +" model, you usually only focus on the "Internet +" model itself
Fundamentals of Cryptography: X.690 and Corresponding BER CER DER Encodings
垃圾回收器CMS和G1
"Introduction to Natural Language Processing Practice" Question Answering Robot Based on Knowledge Graph
typescript35-class的构造函数
bool Frame::PosInGrid(const cv::KeyPoint &kp, int &posX, int &posY)
R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、编写自定义三线表结构(将因子变量细粒度化重新构建三线图)、自定义修改描述性统计参数输出自定义统计量
『网易实习』周记(二)
Effects of Scraping and Aggregation
typescript29-枚举类型的特点和原理
typescript31-any类型
Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
编码经验之谈
电子制造仓储条码管理系统解决方案
typescript38-class的构造函数实例方法继承(implement)
Constructor instance method inheritance of typescript38-class (implement)
Day116. Shangyitong: Details of appointment registration ※