博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【一天一道LeetCode】#81. Search in Rotated Sorted Array II
阅读量:4197 次
发布时间:2019-05-26

本文共 1525 字,大约阅读时间需要 5 分钟。

一天一道LeetCode

本系列文章已全部上传至我的github,地址:

欢迎大家关注我的新浪微博,
欢迎转载,转载请注明出处

(一)题目

Follow up for “Search in Rotated Sorted Array”:

What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

(二)解题

题目大意:在旋转过的有序数组中查找一个指定值。

可以参考

在I的基础上,允许数组中的数重复,那么针对这种情况3,4,3就只能一个一个查找了,没办法用二分来查找。

除上述特殊情况,都可以先确定数组的旋转中心,即最大值和最小值的交界。

然后确定目标数属于那一边,再用二分法查找。

class Solution {public:    bool search(vector
& nums, int target) { int len = nums.size(); int i = 0; int j = len - 1; int p = 0; bool isfind = false; if(nums[0]==nums[len-1]){
//数组头尾相等属于特殊情况,只能挨个查找了 return find(nums.begin(),nums.end(),target)!=nums.end(); } if (nums[0]>nums[len-1])//一般情况 { while (i < j)//二分法找出最大值和最小值的交界 { if (i == j - 1) { isfind = true; break; } int mid = (i + j) / 2; if (nums[i] <= nums[mid]) i = mid; if (nums[j] >= nums[mid]) j = mid; } } if (isfind)//如果找到了,就确认目标数所在的分区 { if (nums[0] <= target) { j = i; i = 0; } if (nums[len - 1] >= target) { i = j; j = len - 1;} } while (i<=j)//在分区中采用二分法来查找 { int mid = (i + j) / 2; if (nums[mid] == target) return true; else if (nums[mid] >target) j = mid-1; else i = mid+1; } return false; }};
你可能感兴趣的文章
【HTML5/CSS/JS】A list of Font Awesome icons and their CSS content values(一)
查看>>
【HTML5/CSS/JS】<br>与<p>标签区别(二)
查看>>
【HTML5/CSS/JS】开发跨平台应用工具的选择(三)
查看>>
【心灵鸡汤】Give it five minutes不要让一个好主意随风而去
查看>>
【React Native】Invariant Violation: Application AwesomeProject has not been registered
查看>>
【ReactNative】真机上无法调试 could not connect to development server
查看>>
【XCode 4.6】常用快捷键 特别是格式化代码ctrl+i
查看>>
【iOS游戏开发】icon那点事 之 实际应用(二)
查看>>
【iOS游戏开发】icon那点事 之 图标设计(三)
查看>>
【IOS游戏开发】之测试发布(Distribution)
查看>>
【IOS游戏开发】之IPA破解原理
查看>>
【一天一道LeetCode】#45. Jump Game II
查看>>
【一天一道LeetCode】#46. Permutations
查看>>
【一天一道LeetCode】#47. Permutations II
查看>>
【一天一道LeetCode】#48. Rotate Image
查看>>
【一天一道LeetCode】#56. Merge Intervals
查看>>
【一天一道LeetCode】#57. Insert Interval
查看>>
【一天一道LeetCode】#58. Length of Last Word
查看>>
【一天一道LeetCode】#59. Spiral Matrix II
查看>>
【一天一道LeetCode】#30. Substring with Concatenation of All Words
查看>>