Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [,,,,,,] might become [,,,,,,]).

You are given a target value to search. If found in the array return its index, otherwise return -.

You may assume no duplicate exists in the array.

Your algorithm's runtime complexity must be in the order of O(log n).

Example :

Input: nums = [,,,,,,], target =
Output:
Example : Input: nums = [,,,,,,], target =
Output: -

断点函数单调性,无非单增,或者只有两段,且各自区间范围内单增

C

4 ms

int search(int* nums, int numsSize, int target) {
if(numsSize == ) return -; int left = , right = numsSize -;
int pivot = ; // turning point
int mid = ;
// search for turning point.
while (left < right)
{
mid = left + (right - left) / ;
if(nums[mid] > nums[right])
{
left = mid + ;
}else{
right = mid;
}
} pivot = left; // search for target.
left = , right = numsSize-;
while (left <= right)
{ //printf("mid:%d, left:%d, right:%d\n", mid, left, right);
mid = left + (right - left) / ;
int realmid = (mid + pivot)%numsSize;
if(nums[realmid] == target)
{
return realmid;
}else if (nums[realmid] < target) {
left = mid + ;
}else {
right = mid - ;
}
}
return -;
}

C++ 0ms

static int x=[](){
// toggle off cout & cin, instead, use printf & scanf
std::ios::sync_with_stdio(false);
// untie cin & cout
cin.tie(NULL);
return ;
}(); class Solution {
public:
int search(vector<int>& nums, int target) { if(nums.empty()) return -; function<int()> _find = [&nums]() -> int {
if(nums.empty()) return ;
int low = , high = nums.size() -;
while(low <= high) {
int mid = (high-low)/ + low;
if(nums[mid] > nums[high]) low = mid+;
else if(nums[mid] < nums[high]) high = mid;
else return mid; }
// return low;
}; function <int(int,int)> binary_search = [&nums](int target, int index) -> int {
if(nums.empty()) return -;
int low =index, high = nums.size() - + index;
while (low <= high) {
int mid = (high-low)/ + low;
int value = nums[mid%nums.size()];
if(target < value) high = mid -;
else if(target > value) low = mid + ;
else
return mid%nums.size();
}
return -;
}; int mid = _find();
return binary_search(target, mid);
}
};

c++ 4ms

/*
Explanation Let's say nums looks like this: [12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] Because it's not fully sorted, we can't do normal binary search. But here comes the trick: If target is let's say 14, then we adjust nums to this, where "inf" means infinity:
[12, 13, 14, 15, 16, 17, 18, 19, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf] If target is let's say 7, then we adjust nums to this:
[-inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] And then we can simply do ordinary binary search. Of course we don't actually adjust the whole array but instead adjust only on the fly only the elements we look at. And the adjustment is done by comparing both the target and the actual element against nums[0]. by StefanPochmann
https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14443/C++-4-lines-4ms by rantos22
*/
class Solution {
public:
int search(vector<int> &nums, int target)
{
auto skip_left = [&]( int x) { return x >= nums[] ? numeric_limits<int>::min() : x; };
auto skip_right = [&] (int x) { return x < nums[] ? numeric_limits<int>::max() : x; };
auto adjust = [&] (int x) { return target < nums[] ? skip_left(x) : skip_right(x); }; auto it = lower_bound( nums.begin(), nums.end(), target, [&] (int x, int y) { return adjust(x) < adjust(y); } ); return it != nums.end() && *it == target ? it-nums.begin() : -;
}
};

c 4ms

/*
The idea is that when rotating the array, there must be one half of the array that is still in sorted order.
For example, 6 7 1 2 3 4 5, the order is disrupted from the point between 7 and 1. So when doing binary search, we can make a judgement that which part is ordered and whether the target is in that range, if yes, continue the search in that half, if not continue in the other half. -- by flyinghx61
https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14472/Java-AC-Solution-using-once-binary-search
*/
int search(int* nums, int numsSize, int target) {
int start = ;
int end = numsSize - ;
while (start <= end){
int mid = (start + end) / ;
if (nums[mid] == target)
return mid; if (nums[start] <= nums[mid]){
if (target < nums[mid] && target >= nums[start])
end = mid - ;
else
start = mid + ;
} if (nums[mid] <= nums[end]){
if (target > nums[mid] && target <= nums[end])
start = mid + ;
else
end = mid - ;
}
}
return -;
}

c 4ms 下面的程序只是结果满足测试用例,实际情况凑巧而已。

/*
The idea is that when rotating the array, there must be one half of the array that is still in sorted order.
For example, 6 7 1 2 3 4 5, the order is disrupted from the point between 7 and 1. So when doing binary search, we can make a judgement that which part is ordered and whether the target is in that range, if yes, continue the search in that half, if not continue in the other half. -- by flyinghx61
https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14472/Java-AC-Solution-using-once-binary-search
*/
int search(int* nums, int numsSize, int target) {
int lo = , hi = numsSize - ;
while (lo <= hi) {
int mid = lo + (hi - lo) / ;
if (target == nums[mid])
return mid;
if (nums[mid] < nums[lo]) {
// 6,7,0,1,2,3,4,5
if (target < nums[mid] || target >= nums[lo])
hi = mid - ;
else
lo = mid + ;
} else {
// 2,3,4,5,6,7,0,1
if (target > nums[mid] || target < nums[lo])
lo = mid + ;
else
hi = mid - ;
}
}
return -;
}

81. Search in Rotated Sorted Array II

. Search in Rotated Sorted Array II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [,,,,,,] might become [,,,,,,]). You are given a target value to search. If found in the array return true, otherwise return false. Example : Input: nums = [,,,,,,], target =
Output: true
Example : Input: nums = [,,,,,,], target =
Output: false
Follow up: This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
Would this affect the run-time complexity? How and why?
bool search(int* nums, int numsSize, int target) {
int l = , r = numsSize - ;
while (l <= r) {
int m = l + (r - l)/;
if (nums[m] == target) return true; //return m in Senumsrch in Rotnumsted numsrrnumsy I
if (nums[l] < nums[m]) { //left hnumslf is sorted
if (nums[l] <= target && target < nums[m])
r = m - ;
else
l = m + ;
} else if (nums[l] > nums[m]) { //right hnumslf is sorted
if (nums[m] < target && target <= nums[r])
l = m + ;
else
r = m - ;
} else l++;
}
return false;
}
/*
1) everytime check if targe == nums[mid], if so, we find it.
2) otherwise, we check if the first half is in order (i.e. nums[left]<=nums[mid])
and if so, go to step 3), otherwise, the second half is in order, go to step 4)
3) check if target in the range of [left, mid-1] (i.e. nums[left]<=target < nums[mid]), if so, do search in the first half, i.e. right = mid-1; otherwise, search in the second half left = mid+1;
4) check if target in the range of [mid+1, right] (i.e. nums[mid]<target <= nums[right]), if so, do search in the second half, i.e. left = mid+1; otherwise search in the first half right = mid-1; The only difference is that due to the existence of duplicates, we can have nums[left] == nums[mid] and in that case, the first half could be out of order (i.e. NOT in the ascending order, e.g. [3 1 2 3 3 3 3]) and we have to deal this case separately. In that case, it is guaranteed that nums[right] also equals to nums[mid], so what we can do is to check if nums[mid]== nums[left] == nums[right] before the original logic, and if so, we can move left and right both towards the middle by 1. and repeat.
dong.wang.1694
*/
class Solution {
public:
bool search(vector<int>& nums, int target) {
int left = , right = nums.size()-, mid; while(left<=right)
{
mid = (left + right) >> ;
if(nums[mid] == target) return true; // the only difference from the first one, trickly case, just updat left and right
if( (nums[left] == nums[mid]) && (nums[right] == nums[mid]) ) {++left; --right;} else if(nums[left] <= nums[mid])
{
if( (nums[left]<=target) && (nums[mid] > target) ) right = mid-;
else left = mid + ;
}
else
{
if((nums[mid] < target) && (nums[right] >= target) ) left = mid+;
else right = mid-;
}
}
return false;
}
};
. Search in Rotated Sorted Array II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [,,,,,,] might become [,,,,,,]). You are given a target value to search. If found in the array return true, otherwise return false. Example : Input: nums = [,,,,,,], target =
Output: true
Example : Input: nums = [,,,,,,], target =
Output: false
Follow up: This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
Would this affect the run-time complexity? How and why?

6ms

bool search(int* nums, int numsSize, int target) {
int l = , r = numsSize - ;
while (l <= r) {
int m = l + (r - l)/;
if (nums[m] == target) return true; //return m in Senumsrch in Rotnumsted numsrrnumsy I
if (nums[l] < nums[m]) { //left hnumslf is sorted
if (nums[l] <= target && target < nums[m])
r = m - ;
else
l = m + ;
} else if (nums[l] > nums[m]) { //right hnumslf is sorted
if (nums[m] < target && target <= nums[r])
l = m + ;
else
r = m - ;
} else l++;
}
return false;
}

4ms

/*
1) everytime check if targe == nums[mid], if so, we find it.
2) otherwise, we check if the first half is in order (i.e. nums[left]<=nums[mid])
and if so, go to step 3), otherwise, the second half is in order, go to step 4)
3) check if target in the range of [left, mid-1] (i.e. nums[left]<=target < nums[mid]), if so, do search in the first half, i.e. right = mid-1; otherwise, search in the second half left = mid+1;
4) check if target in the range of [mid+1, right] (i.e. nums[mid]<target <= nums[right]), if so, do search in the second half, i.e. left = mid+1; otherwise search in the first half right = mid-1; The only difference is that due to the existence of duplicates, we can have nums[left] == nums[mid] and in that case, the first half could be out of order (i.e. NOT in the ascending order, e.g. [3 1 2 3 3 3 3]) and we have to deal this case separately. In that case, it is guaranteed that nums[right] also equals to nums[mid], so what we can do is to check if nums[mid]== nums[left] == nums[right] before the original logic, and if so, we can move left and right both towards the middle by 1. and repeat.
dong.wang.1694
*/
class Solution {
public:
bool search(vector<int>& nums, int target) {
int left = , right = nums.size()-, mid; while(left<=right)
{
mid = (left + right) >> ;
if(nums[mid] == target) return true; // the only difference from the first one, trickly case, just updat left and right
if( (nums[left] == nums[mid]) && (nums[right] == nums[mid]) ) {++left; --right;} else if(nums[left] <= nums[mid])
{
if( (nums[left]<=target) && (nums[mid] > target) ) right = mid-;
else left = mid + ;
}
else
{
if((nums[mid] < target) && (nums[right] >= target) ) left = mid+;
else right = mid-;
}
}
return false;
}
};

33. Search in Rotated Sorted Array & 81. Search in Rotated Sorted Array II的更多相关文章

  1. leetcode 153. Find Minimum in Rotated Sorted Array 、154. Find Minimum in Rotated Sorted Array II 、33. Search in Rotated Sorted Array 、81. Search in Rotated Sorted Array II 、704. Binary Search

    这4个题都是针对旋转的排序数组.其中153.154是在旋转的排序数组中找最小值,33.81是在旋转的排序数组中找一个固定的值.且153和33都是没有重复数值的数组,154.81都是针对各自问题的版本1 ...

  2. LeetCode 81 Search in Rotated Sorted Array II [binary search] <c++>

    LeetCode 81 Search in Rotated Sorted Array II [binary search] <c++> 给出排序好的一维有重复元素的数组,随机取一个位置断开 ...

  3. LeetCode 33 Search in Rotated Sorted Array [binary search] <c++>

    LeetCode 33 Search in Rotated Sorted Array [binary search] <c++> 给出排序好的一维无重复元素的数组,随机取一个位置断开,把前 ...

  4. 【Leetcode】81. Search in Rotated Sorted Array II

    Question: Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? ...

  5. [LeetCode] 81. Search in Rotated Sorted Array II 在旋转有序数组中搜索之二

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...

  6. [LeetCode] 81. Search in Rotated Sorted Array II 在旋转有序数组中搜索 II

    Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would this ...

  7. 【LeetCode】81. Search in Rotated Sorted Array II 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/search-in ...

  8. LeetCode 81. Search in Rotated Sorted Array II(在旋转有序序列中搜索之二)

    Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would this ...

  9. 81. Search in Rotated Sorted Array II (中等)

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...

随机推荐

  1. C_数据结构_数组的修改和删除

    #include<stdio.h> typedef struct Node { int a,b; }node; node c[]; int n; void print() { int i; ...

  2. python-知识回顾-16

    知识回顾 小数据池:int -5~256str 特殊字符,*数字20 ascii : 8位 1字节 表示1个字符unicode 32位 4个字节 表示一个字符utf- 8 1个英文 8位,1个字节 欧 ...

  3. linux书籍

    <鸟哥私房菜-基础版> <实战LINUX_SHELL编程与服务器管理> <LINUX命令行与SHELL脚本编程大全第2版].布卢姆.扫描版> <Linux初学 ...

  4. BugPhobia回顾篇章:团队Beta 阶段工作分析

    0x00:序言 1 universe, 9 planets, 204 countries,809 islands, 7 seas, and i had the privilege to meet yo ...

  5. 结对项目https://github.com/bxoing1994/test/blob/master/源代码

    所选项目名称:文本替换      结对人:曲承玉 github地址 :https://github.com/bxoing1994/test/blob/master/源代码 结对人github地址:ht ...

  6. logback基本入门

    1. logback的定义 Logback是由log4j创始人设计的另一个开源日志组件,官方网站: http://logback.qos.ch.它当前分为下面下个模块: logback-core:其它 ...

  7. JQuery基础-- Ajax

    基本格式: get: $.get("url",data,function(res){   #.....   }) post: $.post("url",data ...

  8. HTML5的placeHolder在IE9下workaround引发的Bug(按下葫芦起了瓢)

    详见StackOverFlow的:Simple jQuery form Validation: Checking for empty .val() failing in ie9 due to plac ...

  9. [转帖]Nginx安装及配置详解 From https://www.cnblogs.com/zhouxinfei/p/7862285.html

    Nginx安装及配置详解   nginx概述 nginx是一款自由的.开源的.高性能的HTTP服务器和反向代理服务器:同时也是一个IMAP.POP3.SMTP代理服务器:nginx可以作为一个HTTP ...

  10. C++与C的区别

    在最开始C++只是C加上了一些面向对象的特性,C++最初的名字为C with Classes.后来C++又提出了一些不同于Class的特性:Exceptions(异常).templates(模板).S ...