Leetcode 33. 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.

题目:有一个有序的数组它会以未知的方式去旋转,如{0,1,2,3,4,5,6,7}  会变成 {4,5,6,7,0,1,2} ,现在给你一个target值用它去在这个未知的旋转过的数组进行查找,有则返回这个数组的下标,没有则返回-1

解题思路:旋转过的数组,你会发现还是有一部分是以有序方式排列的,然后利用数组中左端点的值去判断左端点到中间的部分是旋转过的区域,或是有序的区域,利用有序的区域可以判断target在不在这块区域(最小值和target比较),通过不断的分治,能找到则返回数组下标,否则返回-1.

 1 #include 
 2 
 3 #include 
 4 
 5 class Solution {
 6 public:
 7     int search(std::vector<int>& nums, int target) {
 8         int begin = 0;
 9         int end = nums.size() - 1;
10         while(begin <= end){
11             int mid = (begin + end) / 2;
12             if (target == nums[mid]){
13                 return mid;
14             }
15             else if (target < nums[mid]){
16                 if (nums[begin] < nums[mid]){
17                     if (target >= nums[begin]){
18                         end = mid - 1;
19                     }
20                     else{
21                         begin = mid + 1;
22                     }
23                 }
24                 else if (nums[begin] > nums[mid]){
25                     end = mid -1;
26                 }
27                 else if (nums[begin] == nums[mid]){
28                     begin = mid + 1;
29                 }
30             }
31             else if (target > nums[mid]){
32                 if (nums[begin] < nums[mid]){
33                     begin = mid + 1;
34                 }
35                 else if (nums[begin] > nums[mid]){
36                     if (target >= nums[begin]){
37                         end = mid - 1;
38                     }
39                     else{
40                         begin = mid + 1;
41                     }
42                 }
43                 else if (nums[begin] == nums[mid]){
44                     begin = mid + 1;
45                 }
46             }
47         }
48         return -1;
49     }
50 };
51 
52 int main(){
53     int test[] = {9, 12, 15, 20, 1, 3, 6, 7};
54     std::vector<int> nums;
55     Solution solve;
56     for (int i = 0; i < 8; i++){
57         nums.push_back(test[i]);
58     }
59     for (int i = 0; i < 22; i++){
60         printf("%d : %d\n", i, solve.search(nums, i));
61     }
62     return 0;
63 }

通过~

Leetcode 33. Search in Rotated Sorted Array_第1张图片

 

转载于:https://www.cnblogs.com/Hwangzhiyoung/p/8641750.html

你可能感兴趣的:(数据结构与算法)