|
2 | 2 |
|
3 | 3 | public class Main {
|
4 | 4 |
|
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 | + } |
13 | 35 | }
|
14 |
| - dfs(digits, new StringBuilder(), res, 0); |
15 |
| - return res; |
| 36 | + |
| 37 | + return -1; |
16 | 38 | }
|
17 | 39 |
|
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; |
23 | 43 |
|
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 | + } |
29 | 64 | }
|
| 65 | + |
| 66 | + return -1; |
30 | 67 | }
|
31 | 68 |
|
32 | 69 | public static void main(String[] args) {
|
|
0 commit comments