当前位置:网站首页>【LeetCode】136. 只出现一次的数字
【LeetCode】136. 只出现一次的数字
2022-08-09 04:55:00 【酥酥~】
题目
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
题解
排序,然后寻找
class Solution {
public:
int singleNumber(vector<int>& nums) {
int len = nums.size();
if(len==1)
return nums[0];
sort(nums.begin(),nums.end());
for(int i=1;i<len-1;i++)
if(nums[i]!=nums[i-1] && nums[i]!=nums[i+1])
return nums[i];
return nums[0] != nums[1] ? nums[0] : nums[len-1];
}
};
异或
1:任何数与自身异或都等于0
2:任何数与0异或都等于自身
class Solution {
public:
int singleNumber(vector<int>& nums) {
int cnt = 0;
for(int i:nums)
cnt ^= i;
return cnt;
}
};
边栏推荐
- Parameters in dynamic libraries cannot be modified through macro definitions or global variables in header files
- 【MLT】MLT多媒体框架生产消费架构解析(二)
- 通讯录(文件版)(C语言)(VS)
- TCP/IP协议中分包与重组原理介绍、分片偏移量的计算方法、IPv4报文格式
- EDI对接 New York & Company案例
- php使用phpoffice/phpspreadsheet导入导出excel表格
- ABP 6.0.0-rc.1的新特性
- 【Harmony OS】【ARK UI】Custom popup
- Still don't know what business intelligence (BI) is?After reading this article, you will understand
- 【日常训练--腾讯精选50】7. 整数反转
猜你喜欢

【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed

leetcode:316. 去除重复字母

C进阶 - 程序的编译(预处理操作) + 链接

2022 Security Officer-A Certificate Special Work Permit Exam Question Bank and Online Mock Exam

【Harmony OS】【ARK UI】ETS 上下文基本操作

如何剪裁svg并压缩

Faced with risk control, what should Amazon do when evaluating self-supporting accounts?

HP路由器和交换机日志分析

浙江DAMA-CDGA/CDGP数据治理认证招生简章

【Harmony OS】【ARK UI】Date Basic Operation
随机推荐
Quantitative Genetics Heritability Calculation 2: Half Siblings and Full Siblings
Golang 常见知识点整理
2022年8月深圳产品经理认证招生简章(NPDP)
Nacos源码安装
[Developers must see] [push kit] Collection of typical problems of push service service 2
【Harmony OS】【ARK UI】Lightweight Data Storage
【暑期每日一题】洛谷 P1176 路径计数2
杰理之一拖二 另一台手机超距 通话会无声【篇】
Understanding ML Cross Validation Fast
perl基础语法归纳
[Harmony OS] [ArkUI] ets development graphics and animation drawing
【Harmony OS】【ARK UI】轻量级数据存储
C进阶-C语言文件操作
Pycharm Debug调试使用+代码调试理解
【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
LeetCode-636. 函数的独占时间
ELTEK电源维修SMPS5000SIL整流器模块故障分析及特点
基于ABP和Magicodes实现Excel导出操作
学习笔记--文件夹处理--代码学习
Masked AutoEncoder论文及实现