Sword refers to offer-40-numbers that appear only once in the array-java

Questions and tests

package sword040;
/*一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
*/
public class main {
	
	public static void main(String[] args) {
		int[][] testTable = {
   
   {1,2},{1,1,2,2,5,6,7,7},{1,2,3,3},{1,1,2,3}};
		for (int[] ito : testTable) {
			test(ito);
		}
	}
		 
	private static void test(int[] ito) {
		Solution solution = new Solution();
		int rtn;
		long begin = System.currentTimeMillis();
		for (int i = 0; i < ito.length; i++) {
		    System.out.print(ito[i]+" ");
		}//开始时打印数组
		int[] num1 = new int[1];
		int[] num2 = new int[1];
		solution.findNumsAppearOnce(ito,num1,num2);//执行程序
		long end = System.currentTimeMillis();		
		System.out.println("rtn1=" + num1[0]);
		System.out.println("rtn2=" + num2[0]);
		System.out.println();
		System.out.println("耗时:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

Solution 1 (didn't figure it out)

Using the property that two identical numbers are XORed to 0, the binary form of the XOR operation result of two non-zero and different numbers must have the property of
1. 1. XOR the array from left to right to get a value of
2. Calculate the position index of the lowest bit 1 of the binary value.
3. Divide the original array into two groups according to whether the index is 1 or 0. The division of the two groups is a logical division, and each group is continuously XORed to get two numbers that appear once.

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        int res=0;
        for(int i=0;i<array.length;i++){
            res ^=array[i];
        }
        int index=0;
        while(true){//有的代码是for循环,且循环次数i<32;我不懂为什么只循环32次?
            if((res>>index&1)==1){
                break;
            }
            index++;
        }
        for (int i=0;i<array.length;i++){
            if((array[i]>>index &1)==1){
                num1[0] ^=array[i];
            }
            else num2[0] ^=array[i];
        }
    }
}

 

Guess you like

Origin blog.csdn.net/xushiyu1996818/article/details/112004250