Skip to content

Commit a1e4ebc

Browse files
add problem 33 and test function
1 parent 0ba3532 commit a1e4ebc

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
3+
4+
* (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
5+
6+
* You are given a target value to search. If found in the array return its index, otherwise return -1.
7+
8+
* You may assume no duplicate exists in the array.
9+
* Created by supercoderx on 2017/8/11.
10+
*/
11+
#include
12+
13+
int search(int *nums, int numsSize, int target) {
14+
if (numsSize == 0)
15+
return -1;
16+
if (numsSize == 1) {
17+
return nums[0] == target ? 0 : -1;
18+
}
19+
int left = 0, right = numsSize - 1, mid, num;
20+
21+
// 寻找最小值,即反转点
22+
while (left < right) {
23+
mid = (left + right) / 2;
24+
if (nums[mid] > nums[right])
25+
left = mid + 1;
26+
else
27+
right = mid;
28+
}
29+
30+
int rot = left;
31+
left = 0;
32+
right = numsSize - 1;
33+
int realMid;
34+
while (left <= right) {
35+
mid = (left + right) / 2;
36+
realMid = (mid + rot) % numsSize;
37+
if (nums[realMid] == target)
38+
return realMid;
39+
else if (nums[realMid] < target)
40+
left = mid + 1;
41+
else
42+
right = mid - 1;
43+
}
44+
return -1;
45+
}
46+
47+
void testSearch() {
48+
int a[] = {3, 1};
49+
printf("%d", search(a, 2, 3));
50+
}

0 commit comments

Comments
 (0)