字符串算法——单一数(Single Number III)

问题:
ven 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].

Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
思路一:这里可以采用异或的方法进行处理,两个相同的值异或之后就是0.
因为int整数在java中是按照补码的方式来的,那么正数和它负值按位与的结果是原始最右边非0位的数字为1,其余位都为0;
这样我们把原来的数组分为两个部分,一部分是和resTwo按位与的结果为0的,另一部分的结果和resTwo按位与的结果为1的,并且那两个不相等的数分别落在这两个组中;这样分别对两组的数异或

class Solution {
    public int[] singleNumber(int[] nums) {
        int diff = 0;
        for (int i = 0;i<nums.length;i++) {
            diff ^= nums[i];
        }
        diff &= -diff;

        //*****************************
        int[] result = new int [2]; //存储返回的两个数
        for(int i =0;i<nums.length;i++)
        {
            if ((nums[i]& diff) == 0) //该元素不在集合中
            {
                result[0] ^= nums[i];
            }
            else // 该元素在集合中
            {
                result[1] ^= nums[i];
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值