40、数组中只出现一次的数字

一、题目

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

二、解法

 1 //num1,num2分别为长度为1的数组。传出参数
 2 //将num1[0],num2[0]设置为返回结果
 3 //1 计算出数组中异或的结果
 4 //2 计算结果中第几个不为1的位置
 5 //3 然后将数组中的数字分为2部分,一部份该位置不为1,一部分为0
 6 //4 然后将这两部分 分别以后得到结果
 7 public class Solution {
 8     public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
 9         //使用异或的方法
10          if(array == null || array.length == 0)
11              return;
12          int temp = array[0];
13          //首先获取array数组中每一个值异或的结果,存储到temp中
14          for(int i = 1; i < array.length; i++)
15              temp ^= array[i];
16          int indexOf1 = Findfirst(temp);
17          for(int i = 0; i < array.length; i++){
18                 if(isBit(array[i],indexOf1))
19                     num1[0] ^= array[i];
20                 else
21                     num2[0] ^= array[i];
22             }
23      }
24     //从右到左找到temp中第一个不为1的位置
25      public int Findfirst(int num){
26          int indexBit = 0;
27          while((num&1)==0 && (indexBit<32)){
28              num = num>>1;
29              indexBit++;
30          }
31          return indexBit;
32      }
33      public boolean isBit(int num,int indexBit){
34             num = num >> indexBit;
35             return (num&1) == 1;
36         }
37 }
 1 package test;
 2 //一个整型数组里除了两个数字之外,其他的数字都出现了两次。
 3 //请写程序找出这两个只出现一次的数字。
 4 public class Main {
 5     public static void FindNumsAppearOnce(int [] array) {
 6         //判断输入数据是否合法
 7         if(array.length == 0 || array == null)
 8             return;
 9         int length = array.length;
10         int rs = array[0];
11         int position;
12         //1、将数组中的数据进行异或,得到结果rs
13         for(int i = 1; i < length; i++){
14             rs ^= array[i];
15         }
16         //2、找到rs结果中从右到左第一位不为0的位置,返回位置position
17         position = findBit(rs);
18         //3、然后进行循环判断array数组中的元素,根据二进制位
19         //在position为1和不为1的分为两部分,将这两部分数据进行异或操作
20         //最终得到结果 
21         int num11 = 0,num22 = 0;
22         for(int i = 0; i < length; i++){
23             if(isBit(array[i],position)){
24                 num11 ^= array[i];
25             }else{
26                 num22 ^= array[i];
27             }
28         }
29         System.out.println(num11 + " " + num22);
30     }
31     public static boolean isBit(int num, int position){
32         num = num >> position;
33         if((num&1) == 1)
34             return true;
35         else
36             return false;
37     }
38     //找到rs结果中从右到左第一位不为0的位置,返回位置position
39     public static int findBit(int rs){
40         int indexOfBit = 0;
41         while((rs&1)==0 && indexOfBit < 32){
42             indexOfBit++;
43             rs = rs>>1;
44         }
45         return indexOfBit;
46     }
47     public static void main(String[] args) {
48         int array[] = {2,4,3,6,3,2,5,5,4,6,3,3,12,13};
49         FindNumsAppearOnce(array);
50     }
51 }
原文地址:https://www.cnblogs.com/fankongkong/p/7456673.html