leetcode33——Search in Rotated Sorted Array

原创 2018年04月16日 16:34:57

题目大意:在旋转排序数组中搜索目标数字是否存在

分析:二分搜索的变形。

代码:转载自https://yq.aliyun.com/articles/861

class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int mid = (r - l) / 2 + l;
if (nums[mid] == target)
return mid;  //比如4 5 6 7 0 1 2
if (nums[mid] < nums[r]) {  //此时mid右侧肯定有序
if (nums[mid]<target && target <= nums[r])
l = mid + 1;
else
r = mid - 1;
}
else {  //此时mid左侧肯定是有序的
if (nums[l] <= target && target<nums[mid]) 
r = mid - 1;
else  //目标数字在较小的一段内
l = mid + 1;
}
}
return -1;
}
};

【LEETCODE】33-Search in Rotated Sorted Array [Python]

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 mig...
  • aliceyangxi1987
  • aliceyangxi1987
  • 2016-01-22 11:26:41
  • 1134

[LeetCode]33.Search in Rotated Sorted Array

【题目】 Search in Rotated Sorted Array  Total Accepted: 5827 Total Submissions: 20925My Submissions...
  • SunnyYoona
  • SunnyYoona
  • 2014-01-15 17:18:33
  • 2846

Search in Rotated Sorted Array -- LeetCode

原题链接: http://oj.leetcode.com/problems/search-in-rotated-sorted-array/  这道题是二分查找Search Insert Positi...
  • linhuanmars
  • linhuanmars
  • 2014-03-05 09:15:45
  • 20122

【LeetCode】Search in Rotated Sorted Array 解题报告

【题目】 Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 ...
  • ljiabin
  • ljiabin
  • 2014-10-25 17:00:36
  • 9949

Search in Rotated Sorted Array II -- LeetCode

原题链接: http://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/  这道题是二分查找Search Insert Pos...
  • linhuanmars
  • linhuanmars
  • 2014-03-06 02:04:55
  • 18344

leetcode 81. Search in Rotated Sorted Array II-旋转数组|二分查找

原题链接:81. Search in Rotated Sorted Array II 【思路-Java、Python】 二分查找实现 本题采用二分法实现,但是比较挠头的是边界问题,而且元素有重复,...
  • happyaaaaaaaaaaa
  • happyaaaaaaaaaaa
  • 2016-06-07 11:34:23
  • 1582

[LeetCode]81.Search in Rotated Sorted Array II

【题目】 Search in Rotated Sorted Array II  Total Accepted: 3749 Total Submissions: 12937My Submissi...
  • SunnyYoona
  • SunnyYoona
  • 2014-01-15 22:29:05
  • 2632

LeetCode 33 — Search in Rotated Sorted Array(C++ Java Python)

题目:http://oj.leetcode.com/problems/search-in-rotated-sorted-array/ Suppose a sorted array is rotate...
  • dragon_dream
  • dragon_dream
  • 2014-04-03 14:20:40
  • 1592

[C++]LeetCode: 43 Search in Rotated Sorted Array

题目: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 ...
  • cinderella_niu
  • cinderella_niu
  • 2014-12-11 21:54:40
  • 624

LeetCode --- 81. Search in Rotated Sorted Array II

题目链接:Search in Rotated Sorted Array II Follow up for "Search in Rotated Sorted Array": What if d...
  • makuiyu
  • makuiyu
  • 2015-04-03 17:03:46
  • 794
收藏助手
不良信息举报
您举报文章:leetcode33——Search in Rotated Sorted Array
举报原因:
原因补充:

(最多只允许输入30个字)