一个数组中有偶数个数相同,需要找出不同的那个数,要求复杂度为O(n)

先介绍java中的一种运算,叫 “异或”,符号为 ‘ ^ ’ ,其主要是对两个操作数进行位的异或运算(操作时候自动转换成二进制数),位相同的取0,相反取1。若两操作数相同时,互相抵消。

例:
1010(10),1110(14),1010(10)

操作 :1010 ^ 1110 = 0100

    0100 ^ 1010 = 1110 => 14

  找出不同的数 14 (看作是一种相互抵消)

见问题:

  一个数组中有偶数个数相同(或者是两两成对,有且仅有一个是单独的数),需要找出不同的那个数,要求复杂度为O(n)

  (如果复杂度不为n的话,解决的方式就有很多了)

见代码:

public class Solution {
    public static int singleNumber(int[] arr) {
        int result = 0;
        int len=arr.length;
        for (int i = 0; i < len; i++)
        {
            result = result ^ arr[i];
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums ={9,8,7,6,9,4,55,55,8,7,6};
        int key= singleNumber(nums);
        System.out.println("不同的数为:"+key);
    }
}

结果为:

猜你喜欢

转载自www.cnblogs.com/Mark-blog/p/12896906.html