此方法应返回在两个数组中找到的最小的类似值。它适用于此输入:
int[] C={1,3,2,1};
int[] D={4,2,5,3,2};
public static int getSmallestSimilar(int[] C, int[] D) {
int n = A.length;
int m = B.length;
Arrays.sort(A);
Arrays.sort(B);
int i = 0;
for (int k = 0; k < n; k++) {
System.out.println( B[i] +"::"+ A[k] );
System.out.println( i +"::"+ k );
if (i < m - 1 && B[i] < A[k])
i += 1;
if (A[k] == B[i])
return A[k];
}
return -1;
}
不幸的是,它不适用于此输入:
int[] A={15,9} and int[] B={6,9,3};
我尝试解决问题,但我不能,请帮助
答案 0 :(得分:0)
l
答案 1 :(得分:0)
k
时, B[i]>A[k]
才会递增
此循环应该有效:
int i = 0,k = 0;
for (;;) {
if(i >= m || k >= n)
return -1; //or anything which implies no match found
System.out.println( B[i] + "::" + A[k] );
System.out.println( i + "::" + k );
if (B[i] < A[k])
i += 1;
if (B[i] > A[k])
k += 1;
if (A[k] == B[i])
return A[k];
}