数组对比 java,在java中比较相同数组的元素

博客讨论了如何有效地比较数组中的元素,指出原始双层循环中存在重复比较的问题。解决方案是通过调整内层循环从i+1开始,确保每个元素仅与其他所有元素比较一次,从而提高效率。此外,还提醒注意循环边界应包含数组的最后一个元素。
摘要由CSDN通过智能技术生成

I am trying to compare elements of the same array. That means that i want to compare the 0 element with every other element, the 1 element with every other element and so on. The problem is that it is not working as intended. . What i do is I have two for loops that go from 0 to array.length-1.. Then i have an if statement that goes as follows: if(a[i]!=a[j+1])

for (int i = 0; i < a.length - 1; i++) {

for (int k = 0; k < a.length - 1; k++) {

if (a[i] != a[k + 1]) {

System.out.println(a[i] + " not the same with " + a[k + 1] + "\n");

}

}

}

解决方案

First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

So, to check all pairs of elements you can do:

for (int i = 0; i < a.length; i++) {

for (int k = 0; k < a.length; k++) {

if (a[i] != a[k]) {

//do stuff

}

}

}

But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

A better approach would be to compare each element i to the rest of the array:

for (int i = 0; i < a.length; i++) {

for (int k = i + 1; k < a.length; k++) {

if (a[i] != a[k]) {

//do stuff

}

}

}

So if you have the indices [1...5] the comparison would go

1 -> 2

1 -> 3

1 -> 4

1 -> 5

2 -> 3

2 -> 4

2 -> 5

3 -> 4

3 -> 5

4 -> 5

So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值