我想找到给定数字x
在排序数组中的首次出现。这是我到目前为止的方法:
public static int firstOccur(int[] A, int x, int start, int end){
int first = start;
int last = end;
int result = -1;
while (first <= last){
int mid = (first+last)/2;
if(A[mid] == x){
result = mid;
firstOccur(A, x, first, mid-1);
return result;
}
else if(A[mid] < x){
first = mid+1;
result = firstOccur(A, x, first, last);
}
else if(A[mid] > x){
last = mid-1;
return firstOccur(A, x, first, last);
}
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the value you are looking for: ");
int val = sc.nextInt();
int[] arr = {1,2,2,2,5};
System.out.println("The first occurence of " + val + " is at index " + firstOccur(arr, val, 0, arr.length-1));
}
运行代码时,该函数适用于数字1 & 5 and anything added
。不幸的是,在提交x=2
时,它返回索引2,这是不正确的。我错过了一个小细节吗?
答案 0 :(得分:3)
您不在这里考虑递归函数的返回值
if(A[mid] == x){
result = mid;
firstOccur(A, x, first, mid-1);
return result;
}
将其更改为
if(A[mid] == x) {
result = mid;
int maybeResultToLeft = firstOccur(A, x, first, mid-1);
if (maybeResultToLeft == -1) {
return result;
}
return maybeResultToLeft;
}
或者单线
return maybeResultToLeft == -1? result : maybeResultToLeft;
我们需要选择当前(x
)元素(如果存在-x
)左侧的元素(maybeResultToLeft != -1
)