Skip to content

Commit cded4a2

Browse files
committed
add q34
1 parent f306cb3 commit cded4a2

File tree

3 files changed

+102
-54
lines changed

3 files changed

+102
-54
lines changed

.idea/workspace.xml

Lines changed: 41 additions & 54 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@
7979

8080
* [q23_合并K个排序链表](/src/分治法/q23_合并K个排序链表)
8181
* [q33_搜索旋转排序数组](/src/分治法/q33_搜索旋转排序数组)
82+
* [q34_在排序数组中查找元素的第一个和最后一个位置](/src/分治法/q34_在排序数组中查找元素的第一个和最后一个位置)
8283

8384
### 动态规划
8485

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package 分治法.q34_在排序数组中查找元素的第一个和最后一个位置;
2+
3+
/**
4+
* 二分法 o(log(n))
5+
*/
6+
public class Solution {
7+
8+
public int[] searchRange(int[] nums, int target) {
9+
if (nums == null || nums.length < 1) {
10+
return new int[]{-1, -1};
11+
}
12+
int midIndex = find(0, nums.length - 1, nums, target);
13+
int[] rs = new int[2];
14+
rs[0] = midIndex;
15+
rs[1] = midIndex;
16+
if (midIndex == -1) {
17+
return rs;
18+
}
19+
while (nums[rs[0]] == target && rs[0] > 0) {
20+
int temp = find(0, rs[0] - 1, nums, target);
21+
if (temp == -1) {
22+
break;
23+
} else {
24+
rs[0] = temp;
25+
}
26+
}
27+
28+
while (nums[rs[1]] == target && rs[1] < nums.length - 1) {
29+
int temp = find(rs[1] + 1, nums.length - 1, nums, target);
30+
if (temp == -1) {
31+
break;
32+
} else {
33+
rs[1] = temp;
34+
}
35+
}
36+
return rs;
37+
}
38+
39+
public int find(int beginIndex, int endIndex, int[] nums, int target) {
40+
if (beginIndex == endIndex) {
41+
if (nums[beginIndex] == target) {
42+
return beginIndex;
43+
} else {
44+
return -1;
45+
}
46+
}
47+
int mid = (endIndex - beginIndex) / 2 + beginIndex;
48+
if (nums[mid] > target) {
49+
return find(beginIndex, mid, nums, target);
50+
} else if (nums[mid] < target) {
51+
return find(mid + 1, endIndex, nums, target);
52+
} else {
53+
return mid;
54+
}
55+
}
56+
57+
public static void main(String[] args) {
58+
new Solution().searchRange(new int[]{2, 2}, 2);
59+
}
60+
}

0 commit comments

Comments
 (0)