当前位置:网站首页>LeetCode136:只出现一次的数字
LeetCode136:只出现一次的数字
2022-08-03 14:05:00 【Hugh.L】
题目
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/single-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分析
这是《数据结构基础》中的第一道题,主要思想是位运算中异或运算,可参考以下:
任何数于0异或为任何数 0 ^ n => n
相同的数异或为0: n ^ n => 0
例如:2 ^ 3 ^ 2 ^ 4 ^ 4等价于 2 ^ 2 ^ 4 ^ 4 ^ 3 => 0 ^ 0 ^3 => 3
故对于本题,想找到只出现一次的元素,只需要将数组中的每个数进行异或运算,出现两次的数异或为0(n ^ n => 0),最后只剩下只出现一次的数(0 ^ n => n)。
实现
本题,个人采用C++实现,原理弄清楚后,还需要了解异或函数【bit_xor()】的使用。具体使用示例整理如下:
#include <algorithm>
#include <functional> // to include bit_xor
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
// declaring the values
int A[] = { 1, 2, 3, 4, 5, 6 };
int B[] = { 6, 7, 8, 4, 5, 0 };
int n = 6;
// defining result
int result[n];
// transform is used to apply bitwise_xor
// on the arguments A and B
transform(A, end(A), B,
result, bit_xor<int>());
// printing the resulting array
cout << "A xor B = ";
for (const int& answer:result)
cout << ' ' << answer;
return 0;
} 上述例子是对于两个数组进行异或,事实上,针对本题对一个数组中所有数进行异或,可以写成
accumulate(nums.begin(),nums.end(),0,bit_xor());综上,可以得出以下代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int a=0;
for(int i=0;i<sizeof(nums);i++)
{
a=accumulate(nums.begin(),nums.end(),0,bit_xor());
}
return a;
}
};边栏推荐
猜你喜欢

Petri网-2、有向网

利用华为云ECS服务器搭建安防视频监控平台【华为云至简致远】

数字孪生的4个最佳实践

Zhang Le: The Golden Triangle of R&D Efficiency and Practice in the Field of Demand and Agile Collaboration|Live Review

网络通信的过程

数据科学家 Agnis Liukis :在ML领域,初学者踩过的5个坑

使用Jetty服务器和Axis2框架技术发布Webservice接口
![[web penetration] detailed explanation of CSRF vulnerability](/img/be/5d6dda8294ab263a14ed03fcd61226.png)
[web penetration] detailed explanation of CSRF vulnerability

162_Power Query is a custom function for quickly merging tables in a folder TableXlsxCsv_2.0

UE4 C disk cache solution
随机推荐
参数量仅0.5B,谷歌代码补全新方法将内部生产效率提升6%
Top 10 free proxy IP software_Domestic static IP proxy software
国产替代风潮下,电子元器件B2B商城系统如何助力企业突围市场竞争
为什么手动启动GBase 8c数据库中GTM节点
VLAN experiment
如何使用matlab实现分段函数「建议收藏」
张乐:研发效能的黄金三角及需求与敏捷协作领域的实践|直播回顾
“芯片法案”通过后,美光承诺在美国扩产
HCIP Fifteenth Day Notes (Three-layer Architecture of Enterprise Network, VLAN and VLAN Configuration)
Php程序员用那个编辑器比较好?
varchar2和varchar2(char)_datetime数据类型
secureCRT连接开发板连接不上问题解决
回流和重绘
MySQL【存储过程与函数】
投资75亿卢比!印度宣布建首座存储芯片组装和封测工厂,将于12月量产
爱可可AI前沿推介(8.3)
厨卫电器行业数字化集采管理系统:优化产业供应结构,实现采购业务流程集中管控
IDO代币预售dapp开发及NFT模式
网络数据集-骨干网和校园网-IP流量
MySQL知识总结 (十二) 数据库相关概念