kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 34. Find First and Last Position of Element in Sorted Array

34. Find First and Last Position of Element in Sorted Array

Difficulty: Medium

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

1
2
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

1
2
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Solution

Language: Java

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
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return new int[] {-1, -1};
}
int left, right = 0;
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
start = mid;
} else if (nums[mid] > target) {
end = mid;
} else {
start = mid;
}
}
if (nums[end] == target) {
right = end;
} else if (nums[start] == target) {
right = start;
} else {
return new int[] {-1, -1};
}
start = 0;
end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
end = mid;
} else if (nums[mid] > target) {
end = mid;
} else {
start = mid;
}
}
if (nums[start] == target) {
left = start;
} else {
left = end;
}
return new int[] {left, right};
}
}
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
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return new int[]{-1, -1};
}
return new int[] {search(nums, target, true), search(nums, target, false)};
}

private int search(int[] nums, int target, boolean isLeft) {
int start = 0, end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
if (isLeft) {
end = mid;
} else {
start = mid;
}
} else if (nums[mid] < target) {
start = mid;
} else {
end = mid;
}
}
if (isLeft) {
if (nums[start] == target) {
return start;
}
if (nums[end] == target) {
return end;
}
} else {
if (nums[end] == target) {
return end;
}
if (nums[start] == target) {
return start;
}
}
return -1;
}
}