我目前正在使用 Java 进行算法开发,最近真的被一个特定的问题卡住了。我一直面临开发两种不同算法的挑战。
我的任务是解决选择问题。选择问题确定一组 N 个数中第 k 个最大的数。
我已经成功实现了第一个算法。我将 N 个数字读入一个数组,通过一些简单的算法对数组进行降序排序,然后返回位置 k 的元素。
注:k = N/2
这是工作代码
public int selectionAlgorithmOne() {
int[] intArray = new int[]{1, 7, 9, 8, 2, 3, 5, 4, 6, 10};
//I sort the array of size N in decreasing order
bubbleSortDecreasingOrder(intArray);
//{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
//I obtain the value of k
int k = intArray.length / 2;
//I print the result
System.out.println(intArray[k]);
}
打印在“5”中的值是正确的!然而,第二种算法有点棘手。
将前k个元素读入数组,并按降序排列。接下来,每个剩余的元素被一个一个地读取。当一个新元素到达时,如果它小于数组中的第 k 个元素,它将被忽略。否则,它被放置在数组中的正确位置,将一个元素从数组中移出。当算法结束时,返回第k个位置的元素作为答案。
不幸的是,我的第二个算法不起作用。它返回错误的值“3”。它应该返回与第一个算法相同的值“5”,但效率更高。
我已经被困了几天了,我真的很难找到解决方案。希望我已经为问题提供了足够的背景信息,如果我可以提供更多信息,请告诉我。提前致谢。
这是非工作代码
public int selectionAlgorithmTwo() {
int[] intArray = new int[]{1, 7, 9, 8, 2, 3, 5, 4, 6, 10};
int arrayLength = intArray.length;
int k = arrayLength / 2;
int[] firstHalf = new int[k];
//I read the first half of the elements into an array
for (int i = 0; i < k; i++) {
firstHalf[i] = intArray[i];
}
//I then sort the first half of the elements in decreasing order
bubbleSort(firstHalf);
for(int i = k; i < arrayLength; i++) {
int val = intArray[i];
//If the new element to insert is >= the kth largest
if (val > firstHalf[k - 1]) {
int pos = 0;
for(; pos < k; pos++) {
if(val > firstHalf[pos]) {
break; //I break once I have the correct position located
}
//I make the swap
for (int j = k - 1; j > pos; j--)
firstHalf[j] = firstHalf[j - 1];
firstHalf[pos] = val;
}
}
}
return firstHalf[k - 1];
}
最佳答案
首先,“位置k的元素”不是第k个元素,而是第k+1个元素。事实上,5 是排序数组的第六个元素。
因此,如果要返回位置 k 的元素,则需要一个 k+1 元素的数组。
因此我添加了 firstHalfLen
变量。
如果您使用 k 元素数组,您永远不会得到 5 作为答案。
在 if (val > firstHalf[k])
block 中,为了找到正确的索引,我更喜欢 while 循环
while ((pos < firstHalfLen) && (val <= firstHalf[pos])) {
pos++;
}
然后交换:
for (int j = k; j > pos; j--) {
firstHalf[j] = firstHalf[j - 1];
}
代码:
int[] intArray = new int[] { 1, 7, 9, 8, 2, 3, 5, 4, 6, 10 };
int arrayLength = intArray.length;
int k = arrayLength / 2;
int firstHalfLen = k + 1;
int[] firstHalf = new int[firstHalfLen];
// I read the first half of the elements into an array
for (int i = 0; i < firstHalfLen; i++) {
firstHalf[i] = intArray[i];
}
//I then sort the first half of the elements in decreasing order
bubbleSort(firstHalf);
for (int i = firstHalfLen; i < arrayLength; i++) {
int val = intArray[i];
// If the new element to insert is >= the kth largest
if (val > firstHalf[k]) {
int pos = 0;
// find index
while ((pos < firstHalfLen) && (val <= firstHalf[pos])) {
pos++;
}
// Swap
for (int j = k; j > pos; j--) {
firstHalf[j] = firstHalf[j - 1];
}
firstHalf[pos] = val;
}
}
return firstHalf[k];
关于java - 开发两种不同的算法来查找数组中的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51278569/