我有一个最小差分算法,我想通过打印减去的实际元素来扩展它。我只是想知道这是不是最好的方法。
public static int findMinimumDifference(int[] arr) {
int minuend = 0; //initialize them here
int subtrahend = 0;
Arrays.sort(arr); //sort the array first
int difference = 0;
if (arr.length == 1) {
difference = arr[0];
}
if (arr.length > 1) {
difference = Math.abs(arr[0] - arr[1]); //This will give only positive integers for difference - e.g. 6 - 7 = -1 = 1
for (int i = 0; i <= arr.length; i++) {
if (i + 1 < arr.length) { //as long as we're not at the end yet
int temp = Math.abs(arr[i] - arr[i + 1]); // temp variable is assigned to difference of consecutive elements i and i + 1
if (temp < difference) // if temp is the new minimum difference, assign difference to temp
difference = temp;
if(arr[i + 1] - arr[i] == difference) {
minuend = arr[i + 1]; //Here's where I assign them
subtrahend = arr[i];
}
}
}
}
if(arr.length == 1) { //If there's only one element it will
//display arr[0] - 0 = arr[0]
//e.g. 12 - 0 = 12
System.out.print(arr[0] + " - " + minuend + " = ");
}
else { //otherwise, show the subtraction
System.out.print(minuend + " - " + subtrahend + " = ");
}
return difference;
}
}这是两个数组的输出,例如:
int[] array1 = {5,16,3,32,6};int[] array2 = {13,22,37,40,11,99,100,222,1000,101,9999,10000};阵列的最小差是:6-5=1 10000 - 9999 =1
注意:我知道第二个数组实际上有另一个子集(99,100),它等于1。我只是还没有弄清楚如何显示这两个集合。我稍后会处理这个问题。
发布于 2016-03-07 00:15:58
Arrays.sort(int[])执行数组内排序,如果您的方法的调用方没有预料到这一点,这可能是不可取的。您可能需要首先通过Arrays.copyOf(int[])复制输入。
int temp = Math.abs(arr[i] - arr[i + 1]);
if (temp < difference) /* ... */由于已按升序对数组进行排序,因此有两种可能的方法:
temp保留为负数,这样您就可以查找最大的负数,例如-1,以找到最小的差值。arr[i + 1] - arr[i],这样以后的比较就可以保持不变。因此,没有必要使用Math.abs()。
在打印值时,您将arr.length = 1与多值数组区别对待,但是通过对初始化minuend和difference的方式进行一些调整,您不必这样做,例如:
int minuend = arr[0];
int difference = Integer.MAX;此外,考虑将差异和数组索引存储在差异最小的地方,这样就不需要记住subtrahend了。
https://codereview.stackexchange.com/questions/122086
复制相似问题