1
+ // https://leetcode.com/problems/search-in-rotated-sorted-array/
2
+ class Solution {
3
+ public:
4
+
5
+ int calcMid (int left, int right) {
6
+ return left + (right - left)/2 ;
7
+ }
8
+
9
+ bool isBorder (vector<int >& nums, int i) {
10
+ if (nums[i] > nums[i+1 ])
11
+ return true ;
12
+ return false ;
13
+ }
14
+
15
+ int binarySearch (vector<int >& nums, int left, int right, int target) {
16
+ int i = calcMid (left, right);
17
+ while (nums[i] != target) {
18
+ if (nums[i] < target)
19
+ left = i;
20
+ else
21
+ right = i;
22
+
23
+ i = calcMid (left, right);
24
+ if (right - left < 2 && nums[i] != target) {
25
+ if (nums[left] == target)
26
+ return left;
27
+ else if (nums[right] == target)
28
+ return right;
29
+ else {
30
+ i = -1 ;
31
+ break ;
32
+ }
33
+ }
34
+ }
35
+ return i;
36
+ }
37
+
38
+ int findArrayBorder (vector<int >& nums, int left, int right) {
39
+ int firstListMax = nums[nums.size ()-1 ];
40
+ int i = calcMid (left, right);
41
+ while (!isBorder (nums, i)) {
42
+ if (nums[i] < firstListMax)
43
+ right = i;
44
+ else
45
+ left = i;
46
+
47
+ i = calcMid (left, right);
48
+ }
49
+ return i;
50
+ }
51
+
52
+ int search (vector<int >& nums, int target) {
53
+ // edge cases:
54
+ if (target == nums[nums.size ()-1 ])
55
+ return nums.size ()-1 ;
56
+ if (target == nums[0 ])
57
+ return 0 ;
58
+ if (nums.size () == 1 )
59
+ return -1 ;
60
+
61
+ int length = nums.size ();
62
+ int firstListBegin = 0 , firstListEnd;
63
+ int secondListBegin, secondListEnd = length - 1 ;
64
+ int targetIdx = -1 ;
65
+
66
+ // check whether the array has been rotated
67
+ if (nums[0 ] > nums[length-1 ]) {
68
+ firstListEnd = findArrayBorder (nums, 0 , length-1 );
69
+ secondListBegin = firstListEnd + 1 ;
70
+
71
+ // edge case
72
+ if (secondListBegin == secondListEnd) {
73
+ if (target == nums[secondListBegin])
74
+ return secondListBegin;
75
+ targetIdx = binarySearch (nums, 0 , firstListEnd, target);
76
+ }
77
+ else if (target <= nums[secondListEnd]) {
78
+ // list 2
79
+ targetIdx = binarySearch (nums, secondListBegin, secondListEnd, target);
80
+ }
81
+ else {
82
+ // list 1
83
+ targetIdx = binarySearch (nums, 0 , firstListEnd, target);
84
+ }
85
+ }
86
+ else {
87
+ targetIdx = binarySearch (nums, 0 , length - 1 , target);
88
+ }
89
+
90
+ return targetIdx;
91
+ }
92
+ };
0 commit comments