[LeetCode] Search in Rotated Sorted Array
This problem is a nice application of binary search. The key lies in how to determine the correct half for target
. Since the array has been rotated, we now need to make some additional checks.
You may run the following code with some examples to see how it works :-)
C (0ms)
1 int search(int* nums, int numsSize, int target) { 2 int l = 0, r = numsSize - 1; 3 while (l <= r) { 4 int mid = (l & r) + ((l ^ r) >> 1); 5 if (nums[mid] == target) return mid; 6 if (nums[mid] > target) { 7 if (nums[l] <= target || nums[mid] < nums[l]) r = mid - 1; 8 else l = mid + 1; 9 } 10 else { 11 if (nums[l] > target || nums[mid] >= nums[l]) l = mid + 1; 12 else r = mid - 1; 13 } 14 } 15 return -1; 16 }
C++ (4ms)
1 class Solution { 2 public: 3 int search(vector<int>& nums, int target) { 4 int l = 0, r = nums.size() - 1; 5 while (l <= r) { 6 int mid = (l & r) + ((l ^ r) >> 1); 7 if (nums[mid] == target) return mid; 8 if (nums[mid] > target) { 9 if (nums[l] <= target || nums[mid] < nums[l]) r = mid - 1; 10 else l = mid + 1; 11 } 12 else { 13 if (nums[l] > target || nums[mid] >= nums[l]) l = mid + 1; 14 else r = mid - 1; 15 } 16 } 17 return -1; 18 } 19 };
Python (40ms)
1 class Solution: 2 # @param {integer[]} nums 3 # @param {integer} target 4 # @return {integer} 5 def search(self, nums, target): 6 l, r = 0, len(nums) - 1 7 while l <= r: 8 mid = (l & r) + ((l ^ r) >> 1) 9 if nums[mid] == target: 10 return mid 11 if nums[mid] > target: 12 if nums[l] <= target or nums[mid] < nums[l]: 13 r = mid - 1 14 else: 15 l = mid + 1 16 else: 17 if nums[l] > target or nums[mid] >= nums[l]: 18 l = mid + 1 19 else: 20 r = mid - 1 21 return -1
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· dotnet 源代码生成器分析器入门
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 一步一步教你部署ktransformers,大内存单显卡用上Deepseek-R1
· 一次Java后端服务间歇性响应慢的问题排查记录