Skip to content

Commit 2f42d5a

Browse files
committed
fd
1 parent edbc9bc commit 2f42d5a

File tree

2 files changed

+61
-24
lines changed

2 files changed

+61
-24
lines changed

leetcode/solution/src/SearchInRotatedSortedArray.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
public class SearchInRotatedSortedArray {
2+
23
/**
3-
* TestCase
4-
* [1, 2], 1/2/3
5-
* [2, 1], 2/1/3
6-
* [1], 1/2
4+
* 给各种情况考虑到位
5+
* 关键是判断范围时要先固定单调区间
6+
* 注意Case[3,1],1
77
*/
88
public int search(int[] nums, int target) {
99
int left = 0, right = nums.length - 1;

leetcode/src/Main.java

Lines changed: 57 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,68 @@
22

33
public class Main {
44

5-
private static final String[] ARR = {
6-
"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
7-
};
8-
9-
public List<String> letterCombinations(String digits) {
10-
List<String> res = new ArrayList<>();
11-
if (digits.length() == 0) {
12-
return res;
5+
public int search(int[] nums, int target) {
6+
int left = 0, right = nums.length - 1;
7+
8+
while (left <= right) {
9+
int mid = left + (right - left) / 2;
10+
11+
if (nums[left] < nums[mid]) {
12+
if (target >= nums[left] && target < nums[mid]) {
13+
right = mid - 1;
14+
} else if (target == nums[mid]) {
15+
return mid;
16+
} else {
17+
left = mid + 1;
18+
}
19+
} else if (nums[left] == nums[mid]) {
20+
if (target == nums[mid]) {
21+
return mid;
22+
} else {
23+
left++;
24+
}
25+
}
26+
else {
27+
if (target > nums[mid] && target <= nums[right]) {
28+
left = mid + 1;
29+
} else if (target == nums[mid]) {
30+
return mid;
31+
} else {
32+
right = mid - 1;
33+
}
34+
}
1335
}
14-
dfs(digits, new StringBuilder(), res, 0);
15-
return res;
36+
37+
return -1;
1638
}
1739

18-
private void dfs(String digits, StringBuilder sb, List<String> res, int start) {
19-
if (start >= digits.length()) {
20-
res.add(sb.toString());
21-
return;
22-
}
40+
// [3,1], 1
41+
public int search2(int[] nums, int target) {
42+
int left = 0, right = nums.length - 1;
2343

24-
int n = digits.charAt(start) - '0';
25-
for (char c : ARR[n].toCharArray()) {
26-
sb.append(c);
27-
dfs(digits, sb, res, start + 1);
28-
sb.setLength(sb.length() - 1);
44+
while (left <= right) {
45+
int mid = left + (right - left) / 2;
46+
47+
if (target == nums[mid]) {
48+
return mid;
49+
}
50+
51+
if (nums[left] <= nums[mid]) {
52+
if (target >= nums[left] && target < nums[mid]) {
53+
right = mid - 1;
54+
} else {
55+
left = mid + 1;
56+
}
57+
} else {
58+
if (target > nums[mid] && target <= nums[right]) {
59+
left = mid + 1;
60+
} else {
61+
right = mid - 1;
62+
}
63+
}
2964
}
65+
66+
return -1;
3067
}
3168

3269
public static void main(String[] args) {

0 commit comments

Comments
 (0)