针对于存在相同元素的数组合并去重

数组的合并去重

小白代码,如有改进,请多多指教。

public class work1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a[]={2,5,9,6,2,4};
		int b[]={2,5,8,2,9,7,2,3,5,6,7,9,10};
		int c[] = rmSame(a,b);
		showArr(c);
	}
	
	//数组遍历
	private static void showArr(int[] a) {
		// TODO Auto-generated method stub
		for (int value : a) {
			System.out.println(value);
		}
	}

	//数组合并去重
	private static int[] rmSame(int[] a, int[] b) {
		// TODO Auto-generated method stub
		int length=a.length+b.length;	//tmpArr数组实际长度
		int tmpArr[]=new int[length];		

		for(int i=0;i<a.length;i++){
			tmpArr[i]=a[i];
		}

		for(int j=0;j<b.length;j++){
			tmpArr[a.length+j]=b[j];
		}
		
		for(int i=0;i<length;i++){	//遍历tmpArr数组
			boolean isTrue=false;		//定义数组挪移开关
			for(int j=i+1;j<length;j++){ //遍历tmpArr数组,并与外层形成对比
				if(tmpArr[i]==tmpArr[j]||isTrue){
					isTrue=true;
					if(j+1!=length){		
						tmpArr[j]=tmpArr[j+1];
					}else{
						tmpArr[j]=0;
						length--;
						i--;
					}
				}
			}
		}		
		return subArr(tmpArr,length);
	}
	
	
	//根据长度截取数组
	private static int[] subArr(int[]a,int b) {
		int arr [] = new int[b];
		for(int i=0;i<b;i++){
			arr[i]=a[i];
		}
		return arr;
	}
}

`

上一篇:PTA(Advanced Level)1046.Shortest Distance


下一篇:Difference Based Metrics for Deep Reinforcement Learning Algorithms