leetcode Single Number I II III

Given an array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

第一题比较简单,直接逐个异或得到的结果就是唯一一个出现一次的数:

public int singleNumber(int[] nums) {
    int xor=0;
    for(int i=0;i<nums.length;i++)
    {
        xor^=nums[i];
    }
    return xor;
}

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

第二题其实是很难想到的,也是博客上看到的解法,思路是,对于一个int型的32位数,对于题干的要求,则每位要不出现3N次,要不出现3N+1次,根据这个思路就可以很容易写出程序了,找出出现3n+1次的每一位,组合起来就是这个出现一次的数了。

public int singleNumber(int[] nums) {
    int result=0;

    for(int i=0;i<32;i++)
    {
        int count=0;
        int mask=1<<i;
        for(int j=0;j<nums.length;j++)
        {
            if((nums[j]&mask)!=0)
            {
                count++;

            }
        }
        if(count%3!=0)
        {
            result|=mask;
        }
    }
    return result;
}

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].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
第三题就更难想了,标准答案的思路是这样的,首先对数组中的所有数进行异或,得到的数其实就是两个不同数异或的结果,然后最巧妙的地方是对该数和该数的补码进行与操作,这样得到的结果是什么呢?可以发现得到的是从右向左第一位为1的数,很显然若两个数不等,则他们的最低位1的位置一定是不同的,通过这个结论就可以写程序了:
public int[] singleNumber(int[] nums) {
   int res=0;
    for(int i=0;i<nums.length;i++)
        res^=nums[i];
    int xor=res&-res;
    int a=0,b=0;
    for(int num:nums){
        if((num&xor)==0)
            a^=num;
        else
            b^=num;
    }
    return new int[]{a,b};
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值