找出数组中重复的元素,或者丢失的元素,前提,数组长度N,元素为1到N

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://xxlcube.blog.csdn.net/article/details/12905329
package demo;

public class ArrayRepetition {

	public static int array[] = {2,3,1,5,6,5};
	
	public static int getMax(int c[]) {
		int len = c.length;
		int max = c[0];
		for(int i=1;i<len;i++) {
			if(max<c[i]) {
				max = c[i];
			}
		}
		return max;
	}
	
	public static void findRepetition(int b[]) {
		int len = b.length;
		int max = getMax(b);
		int c[] = new int[max+1];
		for(int i=0;i<len;i++) {
			++c[b[i]];
		}
		for(int i=0;i<max+1;i++) {
			if(c[i]==0&&i!=0) {
				System.out.print("[丢失的元素是"+i+"]");
			}
			if(c[i]==2&&i!=0) {
				System.out.print("[重复的元素是"+i+"]");
			}
			System.out.print(c[i]+",");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		findRepetition(array);
	}

}

展开阅读全文

没有更多推荐了,返回首页