Hallo Leute, warum muss ich in static int search Methode die folgende statement hinzufügen?
Wenn es nur als mögliche Antwort dient (so steht das zumindest in der Aufgabenstellung), könnte ich es auch als "int ans = 0;" deklarieren? Aber wenn ich das mache, gibt mir das Programm die folgende Ausgabe :
Java:
int ans = -1;
Wenn es nur als mögliche Antwort dient (so steht das zumindest in der Aufgabenstellung), könnte ich es auch als "int ans = 0;" deklarieren? Aber wenn ich das mache, gibt mir das Programm die folgende Ausgabe :
Java:
//https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
public class FirstAndLastPosition {
public static void main(String[] args) {
}
public int[] searchRange(int[] nums, int target) {
//If the value is not in range return {-1,-1}
//0 index: -1 -> start
//1 index: -1 -> end
int[] ans = {-1,-1};
//checking for start value
int start = search(nums, target, true);
//checking for end value
int end = search(nums, target, false);
//Updating the answer. In other words, updating int[] ans = {-1,-1}
ans[0] = start;
ans[1] = end;
//If the value is not in range return {-1,-1}
return ans;
}
//this function just returns the index value of target
static int search(int[] nums, int target, boolean findStartIndex) {
//my potential answer is initially -1
int ans = -1;
int start = 0;
int end = nums.length -1;
while (start<=end) {
int mid = start + (end - start) / 2;
if (target < nums[mid]) {
end = mid-1;
} else if (target > nums[mid]) {
start = mid+1;
} else {
//potential ans found
ans = mid;
//if more target values are on the left -> end = mid - 1;
if (findStartIndex == true) {
end = mid - 1;
//if more target values are on the right -> start = mid + 1;
} else {
start = mid + 1;
}
}
}
//my potential answer is initially -1
return ans;
}
}