Java learning manuals :( data structures and algorithms - array) How to find a unique array of repeating elements?

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/MaybeForever/article/details/100901077

topic:

The array a [N], 1 ~ N-1 N-1 the number of which is stored in a [N], where a number of repeated once. Write a function to find the duplicate numbers. It requires that each array element can only visit once, and without an auxiliary storage space.

method one:

Since the subject of the request of each array element can access only once, and without an auxiliary storage space, since only one number is repeatedly and continuously, so that the array can be summed and subtracted in the 1 ~ N-1, is also desired to the number of repetitions.

Method Two:

XOR method. After each two distinct numbers perform XOR operation result is 1; the number of each of two identical XOR operation executed after the result is zero. (XOR commutative and associative law)

(Method II element access times, does not meet the meaning of the questions)

code show as below:

package com.haobi;

public class Test16 {
	public static void main(String[] args) {
		int a[] = {1,2,1,3,4};
		System.out.println(findDup_2(a));
	}
	
	//方法一
	public static int findDup_1(int[] a) {
		int tmp1 = 0;//连续数组求和
		int tmp2 = 0;//数组求和
		for(int i=0;i<a.length-1;i++) {
			tmp1 += (i+1);
			tmp2 += a[i];
		}
		tmp2 += a[a.length-1];
		int result = tmp2 - tmp1;
		return result;
	}
	
	//方法二
	public static int findDup_2(int[] a) {
		int result = 0;
		for(int i=0;i<a.length;i++) {
			result ^= a[i];
		}
		for(int i=1;i<a.length;i++) {
			result ^= i;
		}
		return result;
	}
	
}

Program output results are as follows:

1

Guess you like

Origin blog.csdn.net/MaybeForever/article/details/100901077