-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindValueRotatedArray.cs
More file actions
105 lines (100 loc) · 2.56 KB
/
FindValueRotatedArray.cs
File metadata and controls
105 lines (100 loc) · 2.56 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// https://leetcode.com/problems/search-in-rotated-sorted-array/
public class Solution
{
public int Search(int[] nums, int target)
{
int left = 0;
int right = nums.Length - 1;
int mid = 0;
while (left <= right)
{
mid = (right + left + 1) / 2;
if (nums[mid] == target)
{
return mid;
}
else if (nums[left] < nums[mid])
{
// left side doesnt contain rotation (sorted)
if (target < nums[mid] && target >= nums[left])
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
else
{
// right side is sorted
if (target > nums[mid] && target <= nums[right])
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
}
return -1;
}
}
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;
}
}
}