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 864be1d

Browse files
Solved 34
1 parent ac0b232 commit 864be1d

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package leetcode.editor.en;
2+
3+
class FindFirstAndLastPositionOfElementInSortedArray {
4+
5+
//leetcode submit region begin(Prohibit modification and deletion)
6+
class Solution {
7+
public int[] searchRange(int[] nums, int target) {
8+
int start = universalBinarySearch(0, nums.length, (i) -> {
9+
if(nums[i] == target && (i == 0 || nums[i - 1] < target)) return 0;
10+
if(nums[i] < target) return 1;
11+
else return -1;
12+
});
13+
int end = universalBinarySearch(0, nums.length, (i) -> {
14+
if(nums[i] == target && (i + 1 == nums.length || nums[i + 1] > target)) return 0;
15+
if(nums[i] > target) return -1;
16+
else return 1;
17+
});
18+
return new int[]{start, end};
19+
}
20+
21+
22+
/**
23+
* Returns the value {@code low <= i < high} for which {@code cmp(i) == 0}, assuming that
24+
* for all {@code j > i}, {@code cmp(j) < 0} and for all {@code j < i}, {@code cmp(j) > 0}.
25+
* @param low lower bound of i (inclusive)
26+
* @param high upper bound of i (exclusive)
27+
* @param cmp function of an integer that returns a valid integer as described above for all
28+
* {@code low <= i < high}
29+
* @return appropriate value of {@code i} such that {@code cmp(i) == 0}. If there are more than one such values,
30+
* may return any of them.
31+
*/
32+
int universalBinarySearch(int low, int high, IntComparator cmp){
33+
while(low < high){
34+
int midpoint = low + high >> 1;
35+
int result = cmp.compare(midpoint);
36+
if(result == 0) return midpoint;
37+
if(result < 0){
38+
high = midpoint;
39+
} else {
40+
low = midpoint + 1;
41+
}
42+
}
43+
return -1;
44+
}
45+
46+
@FunctionalInterface
47+
interface IntComparator {
48+
/**
49+
* Determines if the desired value is the given one (zero), a smaller one (negative value) or a greater
50+
* one (positive value).
51+
*/
52+
int compare(int index);
53+
}
54+
}
55+
//leetcode submit region end(Prohibit modification and deletion)
56+
57+
58+
}

0 commit comments

Comments
(0)

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