【发布时间】:2018-04-01 18:00:59
【问题描述】:
我制作了以下程序并实现了合并排序,它对用户填充的数组进行排序,然后从数组中选择任何重复的值。但是,我在主要方法中有一个小问题。示例:我输入数字 4 3 次,它会显示“duplicate: 4”两次;我的目标是让它只显示一次,与有多少个 4 重复无关。谢谢大家。
import java.util.*;
`public class Question6` {
static void mergeSort(int arr1[], int o, int k, int x) {
int num1 = k - o + 1;
int num2 = x - k;
int temp1[] = new int [num1]; //creation of two temporary arrays to store in
int temp2[] = new int [num2];
for (int i=0; i<num1; ++i) //for loops to copy the data to the temporary arrays
temp1[i] = arr1[o + i];
for (int j=0; j<num2; ++j)
temp2[j] = arr1[k + o + j];
int i = 0, j = 0; //starting position of temporary arrays
int s = l; //starting position of the merged two temporary arrays
while (i < num1 && j < num2) {
if (temp1[i] <= temp2[j]) {
arr1[s] = temp1[i];
i++;
}
else {
arr1[s] = temp2[j];
j++;
}
s++;
}
//code to copy elements from temp1
while (i < num1)
{
arr1[s] = temp1[i];
i++;
s++;
}
//code to copy elements from temp2
while (j < num2)
{
arr1[s] = temp2[j];
j++;
s++;
}
}
/
void forSorting(int arr2[], int o, int x) //main method that carries out merge sort
{
if (o < x)
{
// Find the middle point
int a = (o+x)/2;
// Sort first and second halves
forSorting(arr2, o, a);
forSorting(arr2, a+1, x);
// Merge the sorted halves
mergeSort(arr2, o, a, x);
}
}
public static void main(String[] args) {
Question6 qs = new Question6();
Scanner sc = new Scanner(System.in);
int [] duplicate = new int[10];
System.out.println("Please input the numbers to be checked for repetition.");
for(int x = 0; x < 10; x++)
{
duplicate[x] = sc.nextInt(); //filling array
}
int length = duplicate.length;
qs.forSorting(duplicate, 0, length-1); //calling method forSorting
System.out.println(Arrays.toString(duplicate)); //displays array
for (int count = 1; count < 10; count++)
{
if (duplicate[count] == duplicate[count - 1]) {
//displays the duplicates
System.out.println("Duplicate: " + duplicate[count]);
}
}
}
}
【问题讨论】:
-
我无法避免插入重复项,因为这是程序的范围,以显示数组中重复多次的任何数字。还是谢谢你!
-
所以使用hasmap,其中数字是键,计数是值。像 (4, 2) 数字 4 重复两次。
-
对hasmaps或集合不太熟悉,这就是为什么我想在这种情况下坚持使用数组
标签: java arrays duplicates