java - 原始for循环和for each循环的区别
伊谢尔伦
伊谢尔伦 2017-04-17 14:42:09
0
1
677
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;
	} 
	
	public int root(int p){
		while(p != id[p])
			p = id[p];
		return p;
	}
	
	public int getid(int p){
		return id[p];
	}
	public int getsize(int p){
		return sz[p];
	}
	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");
	}

	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];
		}
	}
	
	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()函数那里,用两种不同的循环最终打印出来的数组是不一样的,想问下为什么会出现这种情况,谢谢大家~

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
迷茫
    public void show(){
        for(int ele:id) {
            // System.out.print(id[ele]+ " ");
            System.out.print(ele+ " ");
        }

        // for(int j=0;j<id.length;j++){
        //     System.out.print(id[j]+ " ");
        // }
        System.out.print("\n");
    }
The

in for(int j=0;j<id.length;j++)j is an index, but the for(int ele:id) in ele is an element, not an index - your name is all named after ele, which is the abbreviation of element.

If your id array is not an int type, it will probably be easier for you to understand.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template