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

来源:互联网 发布:安装美工刀片的圆规 编辑:程序博客网 时间:2024/06/05 13:21

问题:
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;    }}
原创粉丝点击