How to find a unique array of number pairs?

First, the bit operation

When handle integer value bits for each possible value of the integer operate directly.
This means you can use masking techniques to get the integer bits.
Second, the XOR functions, eliminate duplication, no-carry adder.
XOR, A ^ A = 0; B ^ 0 = B;
Third, Sign: writing the final result of two solutions, contrast.

Fourth, the title used two methods assisted method and an array of exclusive or eliminate solution

import java.util.Arrays;
import java.util.Random;

public class 题1_如何找数组中唯一成对的那个数 {
	static int N = 10;
	static int[] arr = new int[N];

	public static void main(String[] args) {
		// 构造数组
		printArr();
		// 辅助数组解法
		helperArr();
		// 异或消除解法
		yihuoArr();
	}

	private static void printArr() {
		// 把元素放入数组中
		for (int i = 0; i < arr.length - 1; i++) {
			arr[i] = i + 1;
		}
		// 最后一个数,是随机数
		arr[arr.length - 1] = new Random().nextInt(N - 1) + 1;
		// 随机下标,0-10
		int index = new Random().nextInt(N);
		// 随机数下标与数组中元素的下标交换
		swap(arr, index, arr.length - 1);
		// 输出数组元素
		System.out.println(Arrays.toString(arr));
	}

	// 暴力破解法,开一个辅助空间
	private static void helperArr() {
		int[] helper = new int[N];
		for (int i = 0; i < N; i++) {
			helper[arr[i]]++;
		}
		for (int i = 0; i < N; i++) {
			if (helper[i] == 2) {
				System.out.println("辅助数组法:"+i);
				break;
			}
		}
	}

	// 异或消除法 A^A^B^C^C=B . A^A=0,B^0=B,.任何数和0做异或都是它自己
	private static void yihuoArr() {
		int x1 = 0;
		//对元素进行异或
		for (int i = 1; i < N; i++) {
			x1 = (x1 ^ i);
		}
		//对数组元素进行异或
		for (int i = 0; i < N; i++) {
			x1 = x1 ^ arr[i];
		}
		System.out.println("异或消除法:" + x1);
	}

//两者数交换算法
	public static void swap(int[] arr, int i, int j) {
		int tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	}
}

 

Published 74 original articles · won praise 32 · views 9995

Guess you like

Origin blog.csdn.net/qq_41629684/article/details/104170691