博客
关于我
[Easy] 136. Single Number
阅读量:356 次
发布时间:2019-03-04

本文共 1909 字,大约阅读时间需要 6 分钟。

136. Single Number

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: 1Example 2:Input: [4,1,2,1,2]Output: 4

Solution

Bit Operation

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

Memory Usage: 12.1 MB, less than 6.17% of C++ online submissions for Single Number.
时间复杂度O(n),空间复杂度O(1)

class Solution {   public:    int singleNumber(vector
& nums) { int a = 0; for(int i = 0; i < nums.size(); i++) { a^=nums[i]; } return a; }};

这是个比较巧妙的方法,采用位运算——异或。根据异或的性质有:

a ⊕ a = 0 , a ⊕ 0 = a , a ⊕ a ⊕ b = b , ( a ⊕ b ) ⊕ ( a ⊕ b ) = ( a ⊕ a ) ⊕ ( b ⊕ b ) = 0 \\ a\oplus a=0, \\ a\oplus 0 = a, \\ a\oplus a\oplus b = b, \\ (a\oplus b) \oplus (a\oplus b) = (a\oplus a) \oplus (b\oplus b) = 0 aa=0,a0=a,aab=b,(ab)(ab)=(aa)(bb)=0
所以,可以总结为:如果相同则对应位为0, 如果不同则对应位为1。我们想要找到一个与众不同的元素,也就是需要每个元素间互相异或,这样所有相同的元素异或均为0,那么剩下的就是我们想要的答案了。

Hash Table

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

Memory Usage: 14 MB, less than 6.17% of C++ online submissions for Single Number.
时间复杂度O(n),空间复杂度O(n)

class Solution{       public:        int singleNumber(vector
& nums){ unordered_map
nums_map; for(int i = 0; i < nums.size(); i++) nums_map[nums[i]]++; for(auto it = nums_map.begin(); it != nums_map.end(); it++) if(it->second == 1) return it->first; return nums[0]; }};

it迭代器:

unordered_map
::iterator it;(*it).first; // the key value (of type Key)(*it).second; // the mapped value (of type T)(*it); // the "element value" (of type pair
)

转载地址:http://kbir.baihongyu.com/

你可能感兴趣的文章
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MYSQL8.0以上忘记root密码
查看>>
Mysql8.0以上重置初始密码的方法
查看>>
mysql8.0新特性-自增变量的持久化
查看>>
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>