当前位置:网站首页>【剑指offer】面试题56-Ⅰ:数组中数字出现的次数Ⅰ
【剑指offer】面试题56-Ⅰ:数组中数字出现的次数Ⅰ
2022-07-27 14:24:00 【Jocelin47】
方法一:查表
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) {
map<int, int> record;
vector<int> result;
for(int i = 0; i < nums.size(); i++)
{
record[nums[i]]++;
}
for(auto ele : record)
{
if( ele.second == 1)
result.push_back(ele.first);
}
return result;
}
};
方法二:异或
1.找到sum中第一位为1的数,可以知道这个结果是两个只出现一次的a和b异或的结果。
我们可以把两个数区分为两部分 所有数中这一位为1的数,所有数中这一位为0的值
这样我们再次遍历所有的数,把所有这一位为1的数进行异或就可以得到这个数这一位为1的数
同理得到这一位为0的数
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) {
int sum = 0;
for( int num : nums )
{
sum ^= num;
}
//找到sum中第一位为1的数,我们可以把两个数区分为两部分 所有数中这一位为1的数,这样我们再次遍历所有的数,把所有这一位为这个数的进行异或就可以得到这个数
//另外一个数是这一位为0的值,我们把零另外分组里面的数取出来了
int flag = 1;
// while( ( sum & flag ) == 0 )
// flag << 1;
flag = sum & (-sum);
vector<int> result(2,0);
for( int num : nums )
{
if( (flag & num) == 0)
{
result[0] ^= num;
}
else
{
result[1] ^= num;
}
}
return result;
}
};
边栏推荐
- TCC
- Spark RPC
- Dan bin Investment Summit: on the importance of asset management!
- Unity最简洁的对象池实现
- 实现自定义Spark优化规则
- 扩展Log4j支持日志文件根据时间分割文件和过期文件自动删除功能
- Some binary bit operations
- Deveco studio2.1 operation item error
- What is the breakthrough point of digital transformation in the electronic manufacturing industry? Lean manufacturing is the key
- reflex
猜你喜欢

Introduction of the connecting circuit between ad7606 and stm32

Unity performance optimization ----- occlusion culling of rendering optimization (GPU)

华为鸿蒙模拟器去除顶部导航栏方法

md 中超链接的解析问题:解析`this.$set()`,`$`前要加空格或转义符 `\`

Unity mouse controls the first person camera perspective

Leetcode 783. binary search tree node minimum distance tree /easy

AssetBundle如何打包

Dan bin Investment Summit: on the importance of asset management!

Google team launches new transformer to optimize panoramic segmentation scheme CVPR 2022

Method of removing top navigation bar in Huawei Hongmeng simulator
随机推荐
《剑指Offer》两个链表的第一个公共结点
Leetcode 240. search two-dimensional matrix II medium
使用双星号代替Math.pow()
After configuring corswebfilter in grain mall, an error is reported: resource sharing error:multiplealloworiginvalues
shell脚本读取文本中的redis命令批量插入redis
/dev/loop1占用100%问题
Unity性能优化------渲染优化(GPU)之LOD(Level of detail)
[0 basic operations research] [super detail] column generation
初探JuiceFS
STM32 can communication filter setting problem
Network device hard core technology insider router Chapter 15 from deer by device to router (Part 2)
generic paradigm
AssetBundle如何打包
Tools - common methods of markdown editor
Leetcode 90. subset II backtracking /medium
一文读懂鼠标滚轮事件(wheelEvent)
MySQL interview 40 consecutive questions, interviewer, if you continue to ask, I will turn my face
STM32F10x_ Hardware I2C read / write EEPROM (standard peripheral library version)
谷粒商城配置CorsWebFilter后,报错:Resource sharing error:MultipleAllowOriginValues
Spark3中Catalog组件设计和自定义扩展Catalog实现