Seventy-nine. Find the unique pair of numbers (bit operation)

1——N, these N numbers are placed in an array containing N+1 elements, only one element value is repeated, and the others only appear once. Each array element can only be accessed once, and an algorithm is designed to find it out; without auxiliary storage space, can an algorithm be designed to implement it?

import java.util.Random;

public class LianXi {
    
    
	//交换函数
	public static void swap(int[] a, int index, int i) {
    
    
		int temp = index;
		index = i;
        i=temp;
	}
	
	public static void main(String[] args){
    
    
		//定义一个长度为N的数组
		int N = 11;
		int []a = new int[N];
		for(int i = 0; i < a.length; i++ ){
    
    
			a[i] = i + 1;
		}
		
		//数组最后一个数随机生成
		a[a.length - 1] = new Random().nextInt(N - 1) + 1;
		
		//随机下标
		int index = new Random().nextInt(N);
		
		//数组最后一个数的下标和随机下标进行交换
		swap(a,index,a.length-1);
		
		//遍历最终的数组
		for(int i = 0; i < a.length; i++){
    
    
			System.out.print(a[i] + " ");
		}
		System.out.println("\n");
		
		//进行异或运算,找出重复元素
		int x1 = 0 ;
		//任意一个数与0异或为这个数本身 : A^0=A
		for(int i = 1; i < N - 1; i++){
    
    
			x1 = x1 ^ i;
		}
		//  A^A = 0 ; A^A^B = B
		for(int i = 0; i < N; i++){
    
    
			x1 = x1 ^ a[i];
		}
		System.out.println(x1);
	}
}

Insert picture description here

Guess you like

Origin blog.csdn.net/JiangYu200015/article/details/112888802