zoukankan      html  css  js  c++  java
  • leetcode-268-Missing Number(异或)

    题目描述:

    Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

    Example 1:

    Input: [3,0,1]
    Output: 2
    

    Example 2:

    Input: [9,6,4,2,3,5,7,0,1]
    Output: 8
    

    Note:
    Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

     

    要完成的函数:

    int missingNumber(vector<int>& nums) 

    说明:

    1、给定一个vector,长度假设为K,那么从vector中找到一个在[0,K]之间没有出现过的数字,返回这个数字。

    2、这道题十分容易,知道异或的同学,这道题都能半分钟内AC。

    异或的原理简单介绍下,比如vector是[0,1,3],那么我们把[0,3]之间的数都跟vector中的数[0,1,3]做异或,结果是0^1^2^3^0^1^3=2,也就能出现那个只出现一次的值。

    为什么能这样,因为异或支持交换律和结合律,上面的式子,我们其实能重新写成(0^0)^(1^1)^2^(3^3)。

    同时,异或的规则是两个相同的数异或结果为0,两个不同的数异或结果是1(二进制的表示方法)

    所以(0^0)结果肯定是0,(1^1)也就是0001^0001=0000=0,(3^3)=0011^0011=0000=0,所以0^2=0000^0010=0010=2。所以最终结果为2。

    我们可以用异或来找到那个只出现一次的数字。

    对于异或更多细节感兴趣的同学,可以看一下笔者之前写的另一篇题解leetcode-136-Single Number

    代码如下:

        int missingNumber(vector<int>& nums) 
        {
            int s1=nums.size(),res=0;
            for(int i=0;i<s1;i++)//跟nums中的元素和[0,k-1]中的数字不断异或
                res=res^nums[i]^i;
            return res^s1;
        }
    

    上述代码实测24ms,beats 91.26% of cpp submissions。

  • 相关阅读:
    hdu4549 M斐波那契数列(矩阵快速幂+费马小定理)
    E. 因数串(EOJ Monthly 2020.7 Sponsored by TuSimple)
    2019春总结作业
    大一下半年学期总结
    ball小游戏
    贪吃蛇
    链接远程仓库
    git自动上传脚本及基本代码
    模板 --游戏
    飞机小游戏
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9117558.html
Copyright © 2011-2022 走看看