Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 47bba4b

Browse files
committed
solve 34.在排序数组中查找元素的第一个和最后一个位置
1 parent 62279be commit 47bba4b

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
* @lc app=leetcode.cn id=34 lang=java
3+
*
4+
* [34] 在排序数组中查找元素的第一个和最后一个位置
5+
*
6+
* https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
7+
*
8+
* algorithms
9+
* Medium (39.56%)
10+
* Likes: 490
11+
* Dislikes: 0
12+
* Total Accepted: 105.8K
13+
* Total Submissions: 265.6K
14+
* Testcase Example: '[5,7,7,8,8,10]\n8'
15+
*
16+
* 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
17+
*
18+
* 你的算法时间复杂度必须是 O(log n) 级别。
19+
*
20+
* 如果数组中不存在目标值,返回 [-1, -1]。
21+
*
22+
* 示例 1:
23+
*
24+
* 输入: nums = [5,7,7,8,8,10], target = 8
25+
* 输出: [3,4]
26+
*
27+
* 示例 2:
28+
*
29+
* 输入: nums = [5,7,7,8,8,10], target = 6
30+
* 输出: [-1,-1]
31+
*
32+
*/
33+
34+
// @lc code=start
35+
class Solution {
36+
public int[] searchRange(int[] nums, int target) {
37+
int left = searchLeft(nums, target, 0, nums.length - 1);
38+
if (left >= nums.length || nums[left] != target) {
39+
return new int[] {-1, -1};
40+
}
41+
42+
int right = searchRight(nums, target, left, nums.length - 1);
43+
return new int[] {left, right};
44+
}
45+
46+
public int searchLeft(int[] nums, int target, int start, int end) {
47+
int left = start;
48+
int right = end;
49+
50+
while (left <= right) {
51+
int mid = left + (right - left) / 2;
52+
if (nums[mid] < target) {
53+
left = mid + 1;
54+
} else if (nums[mid] > target) {
55+
right = mid - 1;
56+
} else if (nums[mid] == target) {
57+
right = mid - 1;
58+
}
59+
}
60+
61+
return left;
62+
}
63+
64+
public int searchRight(int[] nums, int target, int start, int end) {
65+
int left = start;
66+
int right = end;
67+
68+
while (left <= right) {
69+
int mid = left + (right - left) / 2;
70+
if (nums[mid] < target) {
71+
left = mid + 1;
72+
} else if (nums[mid] > target) {
73+
right = mid - 1;
74+
} else if (nums[mid] == target) {
75+
left = mid + 1;
76+
}
77+
}
78+
79+
return right;
80+
}
81+
}
82+
// @lc code=end
83+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /