gpt4 book ai didi

java - 键入数组时 for 循环和 for each 循环的区别

转载 作者:行者123 更新时间:2023-11-29 05:01:18 27 4
gpt4 key购买 nike

public class WeightedQuickUnionUF {
private int[] id;
private int[] sz;

public WeightedQuickUnionUF(int N){
id = new int[N];
sz = new int[N];
for(int i=0;i<N;i++)
id[i] = i;
for(int j=0;j<N;j++)
sz[j] = 1;
}

// find the root of that number
public int root(int p){
while(p != id[p])
// // Follow links to find a root.
p = id[p];
return p;
}

public int getid(int p){
return id[p];
}
public int getsize(int p){
return sz[p];
}

// print the array
// I use 2 ways to print the final array, but the results are different
public void show(){
for(int ele:id)
System.out.print(id[ele]+ " ");
for(int j=0;j<id.length;j++)
System.out.print(id[j]+ " ");
System.out.print("\n");
}
// link two trees, the root of the smaller one will be linked to the
// root of the larger one
public void union(int p, int q){
int rootp = root(p);
int rootq = root(q);
if(sz[rootp] < sz[rootq]){
id[rootp] = rootq;
sz[rootq] += sz[rootp];
}
else{
id[rootq] = rootp;
sz[rootp] += sz[rootq];
}
}
// test the class I have defined
public static void main(String args[]){
WeightedQuickUnionUF test1 = new WeightedQuickUnionUF(10);
test1.union(6, 0);
test1.union(1, 7);
test1.union(7, 9);
test1.union(8, 9);
test1.union(8, 5);
test1.union(4, 2);
test1.union(9, 3);
test1.union(4, 0);
test1.union(3, 0);
test1.show();
}
}

我的问题是关于函数 show() 的性能。我使用 2 种方法打印相同的数组,但结果不同。这段代码的正确输出应该是 6 1 4 1 1 1 4 1 1 1,这意味着 for 循环可以给我正确的答案。但是 for each 循环不能做正确的事情。

最佳答案

for-each loop行为并不像您预期​​的那样。也就是说,

for(int ele : id)
System.out.print(id[ele]+ " ");

应该是这样的(我建议使用大括号)

for (int ele : id) {
System.out.print(ele + " ");
}

关于java - 键入数组时 for 循环和 for each 循环的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32031313/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com