Skip to content

Commit 011e8a5

Browse files
authored
Improved task 34.
1 parent 1f0694a commit 011e8a5

File tree

2 files changed

+15
-6
lines changed
  • src
    • main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array
    • test/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array

2 files changed

+15
-6
lines changed

src/main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/Solution.java

+1-6
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,10 @@
22

33
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Binary_Search
44
// #Algorithm_II_Day_1_Binary_Search #Binary_Search_I_Day_5
5-
// #2022_02_18_Time_1_ms_(30.87%)_Space_47.1_MB_(20.91%)
5+
// #2022_04_30_Time_0_ms_(100.00%)_Space_45.7_MB_(81.00%)
66

7-
@SuppressWarnings("unused")
87
public class Solution {
98
public int[] searchRange(int[] nums, int target) {
10-
int l = 0;
11-
int r = nums.length - 1;
129
int[] ans = new int[2];
1310
ans[0] = helper(nums, target, false);
1411
ans[1] = helper(nums, target, true);
@@ -24,14 +21,12 @@ private int helper(int[] nums, int target, boolean equals) {
2421
if (nums[mid] == target) {
2522
result = mid;
2623
}
27-
2824
if (nums[mid] < target || (nums[mid] == target && equals)) {
2925
l = mid + 1;
3026
} else {
3127
r = mid - 1;
3228
}
3329
}
34-
3530
return result;
3631
}
3732
}

src/test/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/SolutionTest.java

+14
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,18 @@ void searchRange() {
1212
int[] actual = new Solution().searchRange(new int[] {5, 7, 7, 8, 8, 10}, 8);
1313
assertThat(actual, equalTo(expected));
1414
}
15+
16+
@Test
17+
void searchRange2() {
18+
int[] expected = new int[] {-1, -1};
19+
int[] actual = new Solution().searchRange(new int[] {5, 7, 7, 8, 8, 10}, 6);
20+
assertThat(actual, equalTo(expected));
21+
}
22+
23+
@Test
24+
void searchRange3() {
25+
int[] expected = new int[] {-1, -1};
26+
int[] actual = new Solution().searchRange(new int[] {}, 0);
27+
assertThat(actual, equalTo(expected));
28+
}
1529
}

0 commit comments

Comments
 (0)