zoukankan      html  css  js  c++  java
  • [LeetCode] 136. Single Number

    Description

    Given a non-empty 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?

    Example 1:

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

    Example 2:

    Input: [4,1,2,1,2]
    Output: 4
    

    Analyse

    一个非空整数数组,有一个元素只出现一次,其他元素都出现两次,找到这个只出现一次的元素

    要求线性时间复杂度,不使用额外的内存

    (刷知乎的时候刷到“力扣上那些让人虎躯一震的题解”,第一道题就是这个,想起来这道题我看过还没想到怎么做,于是打开LeetCode继续做这个题,还真让我想到了,难怪是道easy题,这篇博客的上部分和下面的部分隔了一个春节)

    思路就是使用异或

    相同为0
    不同为1

    nums里所有的数作异或运算得到的就是只出现一次的那个数

    2 ^ 2 ^ 1 = 1

    同时异或也是支持交换律的

    2 ^ 1 ^ 2 = 1

    与0异或值不变

    2 ^ 0 = 2

    最终代码如下

    int singleNumber(vector<int>& nums)
    {
        int result = nums[0];
        for (int i = 1; i < nums.size(); i++)
        {
            result = result ^ nums[i];
        }
        return result;
    }
    

    Result

    Runtime: 16 ms, faster than 94.61% of C++ online submissions for Single Number.

    Memory Usage: 9.6 MB, less than 100.00% of C++ online submissions for Single Number.

  • 相关阅读:
    Javascript常用代码
    Node.cluster
    swift3.0 hello swift(1)
    vs2013 linq to mysql
    ThinkPHP5作业管理系统中处理学生未交作业与已交作业信息
    ThinkPHP5 Model分层及多对多关联的建立
    ThinkPHP5中Session的使用
    用户登陆模块的后端实现
    使用BootStrapValidator来完成前端输入验证
    空间session失效的解决方法
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10403616.html
Copyright © 2011-2022 走看看