-
Notifications
You must be signed in to change notification settings - Fork 0
/
33. Search in Rotated Sorted Array
104 lines (82 loc) · 2.83 KB
/
33. Search in Rotated Sorted Array
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
/*
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
*/
/*
Idea: В массиве любое число после точки поворота менье любого числа до точки поворота
Any number after the rotation index is less than any number before the rotation index
7
6
5
4 _____________
2
1
0
*/
class Solution {
public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
// min number index
int rotationStartIdx = findRotationStartIndex(nums);
if (rotationStartIdx == -1) {
return binarySearch(nums, target, 0, nums.length - 1);
}
if (nums[rotationStartIdx] == target) {
return rotationStartIdx;
}
if (nums[0] <= target && target <= nums[rotationStartIdx - 1]) {
return binarySearch(nums, target, 0, rotationStartIdx - 1);
} else {
return binarySearch(nums, target, rotationStartIdx, nums.length - 1);
}
}
/**
* In a sorter array finds the index from which rotation starts.
* For Example:
* array: 4 5 6 7 0 1 2
* index: 0 1 2 3 4 5 6
* will return 4
*
* @param nums - sorted array at some point rotated.
* @return rotations start index
*/
private int findRotationStartIndex(int[] nums) {
int rightNum = nums[nums.length - 1];
int leftIdx = 0;
int rightIdx = nums.length - 1;
while (leftIdx <= rightIdx) {
int middleIdx = leftIdx + (rightIdx - leftIdx) / 2;
if (nums[middleIdx] > rightNum && nums[middleIdx + 1] <= rightNum) {
return middleIdx + 1;
}
if (nums[middleIdx] > rightNum && nums[middleIdx + 1] > rightNum) {
leftIdx = middleIdx + 1;
} else {
rightIdx = middleIdx - 1;
}
}
return -1;
}
private int binarySearch(int[] nums, int target, int leftIdx, int rightIdx) {
while (leftIdx <= rightIdx) {
int middleIdx = leftIdx + (rightIdx - leftIdx) / 2;
if (nums[middleIdx] == target) {
return middleIdx;
}
if (target < nums[middleIdx]) {
rightIdx = middleIdx - 1;
} else {
leftIdx = middleIdx + 1;
}
}
return -1;
}
}