Single Number I+II+III

Expected:linear runtime complexity, constant space complexity.(像当初的我直接用关联容器暴力解决…)

Single Number I

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

public class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for(int i=0;i<nums.length;i++)
            result = result ^ nums[i];
        return result;
    }
}
//只有这道完全是自己想到的...因为想到一种用位操作实现两数互换的方法(不需要用temp):
// A = A^B;
// B = A^B;
// A = A^B;

Single Number II

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

//方法一(Single Number I也可以用)
//统计数组中的数字每一位上'1'的个数,对3取余即可得到SingleNumber在该位是'0'还是'1'
public class Solution {
    public int singleNumber(int[] nums) {
        int temp;
        int result = 0;
        for(int i=0;i<32;i++){
            temp = 0;
            for(int j=0;j<nums.length;j++){
                temp += (nums[j]>>i)&1;
            }
            temp %= 3;
            result |= (temp<<i);
        }

        return result;
    }
}

//方法二:amazing...
public class Solution {
    public int singleNumber(int[] nums) {
        int one=0;
        int two=0;
        int i,j,k;
        //其中的one代表目前为止number出现了一次
        //two代表出现了两次
        //three代表出现了三次
        for(i=0; i<nums.length; i++)
        {
            two = two |(one&nums[i]);//当one为'1'时,two为'1'(已经出现过一次,现在又出现一次),当one为‘0’时,two不变
            one = one^nums[i];//出现了奇数次则为非0

            int three = two&one;
            two = two^three; //当one和two都达到非零时,用three将two置零
            one = one^three; //用three将one置零
        }

        return one|two;
    }
}

Single Number III

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

public class Solution {
    public int[] singleNumber(int[] nums) {
        int attempt = 0;
        for(int i=0;i<nums.length;i++){
            attempt ^= nums[i];//得到两个结果的异或
        }
        //如何把二者分离?
        //找到异或结果中某位为'1'的位置,然后将原数组中此位为'1'的分为一类,为'0'的分为一类
        //为了计算考虑,通常寻找最后一个'1'的位置,而且有一个很巧妙的公式:
        int lastOne = attempt & (~(attempt-1));
        int a = 0;
        int b = 0;
        for(int i=0;i<nums.length;i++){
            if( (nums[i]&lastOne) == 0) a^=nums[i];
            else b^=nums[i];
        }

        int[] result = new int[2];
        result[0] = a;
        result[1] = b;

        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值