-
Notifications
You must be signed in to change notification settings - Fork 112
/
033-SearchInRotatedSortedArray.cs
56 lines (51 loc) · 1.56 KB
/
033-SearchInRotatedSortedArray.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//-----------------------------------------------------------------------------
// Runtime: 84ms
// Memory Usage: 24.8 MB
// Link: https://leetcode.com/submissions/detail/327026043/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _033_SearchInRotatedSortedArray
{
public int Search(int[] nums, int target)
{
int lo = 0, hi = nums.Length - 1;
int mid, loValue, hiValue, midValue;
while (lo <= hi)
{
loValue = nums[lo];
hiValue = nums[hi];
if (loValue <= hiValue && (target < loValue || target > hiValue))
{
return -1;
}
mid = lo + (hi - lo) / 2;
midValue = nums[mid];
if (target == midValue) { return mid; }
if (loValue <= midValue)
{
if (loValue <= target && target < midValue)
{
hi = mid - 1;
}
else
{
lo = mid + 1;
}
}
else
{
if (target <= hiValue && midValue < target)
{
lo = mid + 1;
}
else
{
hi = mid - 1;
}
}
}
return -1;
}
}
}