260. Single Number III

来源:互联网 发布:aspen软件介绍 编辑:程序博客网 时间:2024/05/31 11:04

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return[3, 5].


思路: 首先通过异或找到那2个不一样数的异或结果,然后根据异或结果找到这两个数不一样的数,即一个当前位为1,一个为0,然后将所有的为1的数异或的结果就是其中一个数,然后将所有当前位为0的数异或得到另一个数。


<span style="font-size:14px;">public class Solution {    public int[] singleNumber(int[] nums) {        int n=nums.length;        int nXor=0;        for(int i=0;i<n;i++){            nXor^=nums[i];        }        int x1=0,x2=0;        int i=1;        while((nXor&1)==0){            nXor>>=1;            i<<=1;        }        for(int j=0;j<n;j++){            if((nums[j]&i)==0)                x1^=nums[j];            else                x2^=nums[j];        }        return new int[]{x1,x2};    }}</span>



0 0
原创粉丝点击