LeetCode 33. Search in Rotated Sorted Array
原题链接在这里:https://leetcode.com/problems/search-in-rotated-sorted-array/
题目:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
).
You are given a target value to search. If found in the array return its index, otherwise return -1
.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2]
, target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2]
, target = 3
Output: -1
题解:
因为rotate, 所以不能直接用Binary Search, 需要进行 二次判定.
通过nums[l] < nums[mid]判断左侧是正常升序,没有rotation, 若是这种情况下 target >= nums[l] && target <= nums[mid] 就在左侧查找,其他情况右侧查找.
否则右侧正常升序,没有rotation, 若是这种情况下target >= nums[mid] && target <= nums[r] 就在右侧查找,其他情况左侧查找.
Time Complexity: O(logn). n = nums.lengthj.
Space: O(1).
AC Java:
1 class Solution { 2 public int search(int[] nums, int target) { 3 if(nums == null || nums.length == 0){ 4 return -1; 5 } 6 7 int l = 0; 8 int r = nums.length - 1; 9 while(l <= r){ 10 int mid = l + (r - l) / 2; 11 if(nums[mid] == target){ 12 return mid; 13 } 14 15 if(nums[mid] < nums[r]){ 16 if(target >= nums[mid] && target <= nums[r]){ 17 l = mid + 1; 18 }else{ 19 r = mid - 1; 20 } 21 }else{ 22 if(target >= nums[l] && target <= nums[mid]){ 23 r = mid - 1; 24 }else{ 25 l = mid + 1; 26 } 27 } 28 } 29 30 return -1; 31 } 32 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· Supergateway:MCP服务器的远程调试与集成工具
· C# 13 中的新增功能实操