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.

  • 相关阅读:
    js实现IE6下png背景透明,超简单,超牛!
    SQLSERVER 动态执行SQL sp_executesql与EXEC
    存储过程中的 SET NOCOUNT ON
    sql CHARINDEX
    css让页面居中
    (转)GridView合集
    (转)智能客户端(SmartClient)
    将程序加到启动组
    SQL时间函数详细说明
    独立存储
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10403616.html
Copyright © 2011-2022 走看看