-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchRotatedArray.cs
More file actions
61 lines (58 loc) · 1.54 KB
/
SearchRotatedArray.cs
File metadata and controls
61 lines (58 loc) · 1.54 KB
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
57
58
59
60
61
// https://leetcode.com/problems/search-in-rotated-sorted-array/submissions/
public class Solution
{
public int Search(int[] nums, int target)
{
if (nums.Length == 0)
return -1;
int pivot = FindMin(nums);
int start = 0;
int end = nums.Length - 1;
int x = ((start + end + 1) / 2) % nums.Length; // x represents the virtual index if it was non pivoted.
int i; // i represents the true index.
while (start <= end)
{
i = (x + pivot) % nums.Length;
if (nums[i] == target)
{
return i;
}
if (nums[i] > target)
{
// Its to the left
end = x - 1;
}
else
{
// Its to the right
start = x + 1;
}
x = ((start + end + 1) / 2) % nums.Length;
}
return -1;
}
public int FindMin(int[] nums)
{
int start = 0;
int end = nums.Length - 1;
int x = ((start + end + 1) / 2) % nums.Length;
while (true)
{
if (nums[(x + nums.Length - 1) % nums.Length] >= nums[x])
{
return x;
}
if (nums[x] >= nums[0])
{
// its to the right
start = x + 1;
}
else
{
// Its to the left
end = x - 1;
}
x = ((start + end + 1) / 2) % nums.Length;
}
}
}