当前位置:网站首页>day260:只出现一次的数字 III
day260:只出现一次的数字 III
2022-06-22 09:19:00 【浅浅望】
问题:
给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。你可以按 任意顺序 返回答案。
进阶:你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?
示例 1:
输入:nums = [1,2,1,3,2,5]
输出:[3,5] 解释:[5, 3] 也是有效的答案。
示例 2:
输入:nums = [-1,0]
输出:[-1,0]
示例 3:
输入:nums = [0,1]
输出:[1,0]
来源:力扣(LeetCode)
题解
思路一:哈希表
利用哈希表存储整型数组中所有元素的个数
提取出个数为1的元素
class Solution {
public int[] singleNumber(int[] nums) {
Map<Integer, Integer> nums_count = new HashMap<>();
for(int i : nums)
nums_count.put(i,nums_count.getOrDefault(i,0)+1);
int[] a = new int[2];
int idx = 0;
for(int i : nums){
if(nums_count.get(i)==1)
a[idx++] = i;
}
return a;
}
}
思路二:异或
已知:0与整数异或的结果为整数本身,两个相同的数异或结果为0。
- 对该整数数组元素循环异或,得到只出现一次两元素的异或结果sum;
- 任选sum二进制数为1的位数k,sum中为1表明此位数上的只出现一次元素的该位的值不同,以此区分两个只出现一次的元素;
- 通过第k位不相同,将数组元素分为两个部分(每个部分仅包含一个单一元素),重新进行异或操作,得到两个只出现一次的元素a[0],a[1]。
class Solution {
public int[] singleNumber(int[] nums) {
int sum = 0;
for(int i : nums) sum ^= i;
int k = -1;
for(int i = Integer.toBinaryString(sum).length(); i>0; i--){
if(((sum >> i) & 1) == 1) k = i;
}
int[] a = new int[2];
for(int i : nums){
if((( i >> k ) & 1) ==1) a[0] ^= i;
else a[1] ^= i;
}
return a;
}
}
边栏推荐
- Value (address) transmission, see the name clearly, don't fall into the ditch
- ModuleNotFoundError: No module named ‘rospy‘,pip也找不到安装包
- Typical cases of final
- Yiwen approaches ZMQ
- 看看volatile你深知多少
- DHCP Relay
- Have you ever paid attention to those classes in the collection that are thread safe?
- simple_ Strtoull character conversion related functions
- 论文笔记:DETR: End-to-End Object Detection with Transformers (from 李沐老师and朱老师)
- 机器学习|nltk_Data下载错误|nltk的stopwords语料下载错误解决方法
猜你喜欢
随机推荐
Double machine hot standby of firewall on ENSP
It is hoped that more and more women will engage in scientific and technological work
Module usage of pytorch: linear model (incomplete)
模糊查询和聚合函数
Volumedetect of ffmpeg
Assert()
[uni app] actual combat summary (including multi terminal packaging)
Mapping multiple exit servers on ENSP
User insight into the video industry in January 2022: active users began to pick up under the influence of holidays
Feedforward and backpropagation
Embedded development terminology concept summary
Sparse array ^ create ^ restore ^ save ^ fetch -- family bucket
C语言刷题 | 判断某年是否只闰年(12)
DOM programming
Alibaba big fish SMS interface PHP version, simplified version Alibaba big fish SMS sending interface PHP instance
Apprentissage automatique | nltk Erreur de téléchargement des données | solution d'erreur de téléchargement du corpus stopwords pour nltk
C语言刷题 | 用putchar输出Love(14)
Debian10配置RSyslog+LoganAlyzer日志服务器
[hdu] P7058 Ink on paper 求最小生成树的最大边
Stream流创建_操作_收集_案例








