LeetCode 题解(189): Single Number III

来源:互联网 发布:入门拳击手套 知乎 编辑:程序博客网 时间:2024/06/15 21:36

题目:

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?
题解:

扫两遍,第一遍全异或得值temp。取temp中最低位不为0的位,其余位置0。如temp = 6 = 0x110,则取0x010。

扫第二遍,所有 i & 0x010 == 0x010的数异或得一个结果,其余数异或得另一个结果。

原理是两个不同的数至少会有一个bit位不同,造成全异或的结果中至少一位为1.那么以该位做区分,即可得两数。

C++版:

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        vector<int> result(2, 0);        int temp = 0;        for(auto i : nums)            temp ^= i;        int i = 1;        while((temp & i) != i)            i = i << 1;        for(auto j : nums) {            if((j & i) == i)                result[0] ^= j;            else                result[1] ^= j;        }        return result;    }};

Java版:

public class Solution {    public int[] singleNumber(int[] nums) {        int[] result = new int[2];        int temp = 0;        for(int i = 0; i < nums.length; i++)            temp ^= nums[i];        int j = 1;        while((temp & j) != j)            j <<= 1;        for(int i = 0; i < nums.length; i++) {            if((nums[i] & j) == j)                result[0] ^= nums[i];            else                result[1] ^= nums[i];        }        return result;    }}

Python版:

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        result = [0, 0]        temp = 0        for i in nums:            temp ^= i        j = 1        while temp & j != j:            j <<= 1        for i in nums:            if i & j == j:                result[0] ^= i            else:                result[1] ^= i        return result

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 苹果7p手机死机怎么办 苹果6s死机了怎么办啊 6s死机了关不了怎么办 爱疯7死机了怎么办 苹果11.4系统老死机怎么办 苹果6震动坏了怎么办 苹果6手机死机了怎么办 苹果x耗电太快怎么办 苹果6升级11.3卡怎么办 苹果6splus耗电快怎么办 苹果手机系统升级后反应慢怎么办 苹果8听筒声音小怎么办 苹果6s通话声音小怎么办 苹果手机通讯录丢失了怎么办 苹果换id通讯录没有了怎么办 华为p7 更新重启怎么办 打电话的图标没了怎么办 苹果手机wifi信号弱怎么办 没电脑想装wifi怎么办 阿巴町手表二维码丢了怎么办 儿童手表二维码丢了怎么办 电话手表二维码丢了怎么办 360儿童手表二维码丢了怎么办 喜书郎电话手表二维码丢了怎么办 微信充话费充错号码怎么办 话费冲到了副卡怎么办 冲话费冲错了怎么办 微信支付未到账怎么办 速卖通修补配件到国外怎么办 速卖通流量低怎么办 速卖通被判定重复铺货怎么办 拼多多商品降权怎么办 运满满有了差评怎么办 房贷款还清后该怎么办 身份证被偷了怎么办啊 苹果手机wifi速度慢怎么办 电脑桌面上的图标不见了怎么办 夏天手机没地方放怎么办 上班手机没地方放怎么办 京东退款未到账怎么办 京东退款失败后怎么办