问题描述
我正在尝试用两个数组制作代码。 除了最小的数目,第二个数组具有与第一个相同的值。 我已经编写了一个代码,其中z是最小的数字。 现在我只想制作一个没有z的新数组,任何反馈将不胜感激。
public static int Second_Tiny() {
int[] ar = {19, 1, 17, 17, -2};
int i;
int z = ar[0];
for (i = 1; i < ar.length; i++) {
if (z >ar[i]) {
z=ar[i];
}
}
}
1楼
Java 8流具有内置功能,可以实现您想要的功能。
public static void main(String[] args) throws Exception {
int[] ar = {19, 1, 17, 17, -2, -2, -2, -2, 5};
// Find the smallest number
int min = Arrays.stream(ar)
.min()
.getAsInt();
// Make a new array without the smallest number
int[] newAr = Arrays
.stream(ar)
.filter(a -> a > min)
.toArray();
// Display the new array
System.out.println(Arrays.toString(newAr));
}
结果:
[19, 1, 17, 17, 5]
否则,您将看到以下内容:
public static void main(String[] args) throws Exception {
int[] ar = {19, 1, 17, 17, -2, -2, -2, -2, 5};
// Find the smallest number
// Count how many times the min number appears
int min = ar[0];
int minCount = 0;
for (int a : ar) {
if (minCount == 0 || a < min) {
min = a;
minCount = 1;
} else if (a == min) {
minCount++;
}
}
// Make a new array without the smallest number
int[] newAr = new int[ar.length - minCount];
int newIndex = 0;
for (int a : ar) {
if (a != min) {
newAr[newIndex] = a;
newIndex++;
}
}
// Display the new array
System.out.println(Arrays.toString(newAr));
}
结果:
[19, 1, 17, 17, 5]
2楼
我认为OP在看到他的评论时走在错误的轨道上:
“我正在尝试找出数组ar []中的第二个最小整数。完成后,我应该得到1的输出。要实现这一目标的方法是制作一个名为newar []的新数组,并使其包含ar []的所有索引,但不包括-2除外。”
这是解决此问题的非常低效的方法。 您将需要进行3次遍历,一次是找到索引最小的元素,另一遍是删除元素(这是一个数组,因此删除元素将需要一整遍),另一遍是再次查找最小的元素。
您应该只执行一次遍历算法,并跟踪最小的两个整数,甚至更好地使用树来提高效率。 这是此问题的最佳答案:
更新:这是具有OP要求,3次通过且没有外部库的算法:
public static int Second_Tiny() {
int[] ar = {19, 1, 17, 17, -2};
//1st pass - find the smallest item on original array
int i;
int z = ar[0];
for (i = 1; i < ar.length; i++) {
if (z >ar[i]){
z=ar[i];
}
}
//2nd pass copy all items except smallest one to 2nd array
int[] ar2 = new int[ar.length-1];
int curIndex = 0;
for (i=0; i<ar.length; i++) {
if (ar[i]==z)
continue;
ar2[curIndex++] = ar[i];
}
//3rd pass - find the smallest item again
z = ar2[0];
for (i = 1; i < ar2.length; i++) {
if (z >ar2[i]){
z=ar2[i];
}
}
return z;
}
3楼
这将获取变量z中指定的元素的索引,然后将第二个数组设置为第一个数组减去一个元素。
本质上,这给出了ar2 = ar1减去元素z
public static int Second_Tiny() {
int[] ar = {19, 1, 17, 17, -2};
int[] ar2;
int i;
int z = ar[0];
int x = 0;
for (i = 1; i < ar.length; i++) {
if (z >ar[i]){
z=ar[i];
x=i;
}
}
ar2 = ArrayUtils.remove(ar, x);
return(z);
}