快捷搜索: 王者荣耀 脱发

找到两个数组中相同元素

题目:

给定两个整型数组a和b,找出其共同元素。
 eg:int[] a={23,12,45,11};
 int[] b={99,33,12,45,67,11}

要找出:12,45,11


package homework2;

public class FindCommon {
	public static void main(String[] args) {
		 int[] a={23,12,45,11,12,12};
		 int[] b={99,33,12,45,67,11,12,12,23};
		 int[] temp=find(a,b);
		 dropSame(temp);
	}
	public static int[] find(int[] a,int[] b) {
		int []temp =new int[a.length];
		int count=0;
		for(int i=0;i<a.length;i++) {
			for(int j=0;j<b.length;j++) {
				if(a[i]==b[j]) {
					temp[count]=a[i];
					count++;
					break;
				}
			}
		}
		return temp;
	}
	public static void dropSame(int[] temp) {
		System.out.print("a和b的相同元素:  ");
		for(int i=0;i<temp.length;i++) {
			boolean flag=true;
			for(int j=i+1;j<temp.length;j++) {
				if(temp[i]==temp[j]) {
					flag=false;
					break;
				}
				
			}
			if(flag==true) {
				System.out.print(temp[i]+"  ");
			}
		}
	}

}
run:

a和b的相同元素: 23 45 11 12

提示一下fin()和dropSame()方法中的两个break很重要

经验分享 程序员 微信小程序 职场和发展