[260]Single Number III
2015-10-14 11:15
246 查看
【题目描述】
Given an array of numbers
once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given
Note:
The order of the result is not important. So in the above example,
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
【思路】
思路和Single Number的类似,依然是用三种方法实现的,个人认为第三种最巧妙,但是在时间紧迫的情况下其实想到前两种更容易。
【代码】
1.
2.
3.
Given an array of numbers
nums, in which exactly two elements appear only
once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given
nums = [1, 2, 1, 3, 2, 5], return
[3, 5].
Note:
The order of the result is not important. So in the above example,
[5, 3]is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
【思路】
思路和Single Number的类似,依然是用三种方法实现的,个人认为第三种最巧妙,但是在时间紧迫的情况下其实想到前两种更容易。
【代码】
1.
class Solution { public: vector<int> singleNumber(vector<int>& nums) { vector<int> ans; int cnt=0; sort(nums.begin(),nums.end()); for(int i=0;i<nums.size()-1;i++){ if(nums[i]==nums[i+1]) i++; else{ ans.push_back(nums[i]); cnt++; } if(cnt==2) return ans; } ans.push_back(nums[nums.size()-1]); return ans; } };
2.
class Solution { public: vector<int> singleNumber(vector<int>& nums) { vector<int> ans; map<int,int> m; for(int i=0;i<nums.size();i++){ if(m.find(nums[i])==m.end()){ m.insert(pair<int,int>(nums[i],nums[i])); } else{ m.erase(m.find(nums[i])); } } map<int,int>::iterator it; it=m.begin(); for(it;it!=m.end();it++){ ans.push_back(it->second); } return ans; } };
3.
class Solution { public: vector<int> singleNumber(vector<int>& nums) { int axorb=0; for(int i=0;i<nums.size();i++){ axorb^=nums[i]; } int lastbit=(axorb & (axorb - 1)) ^ axorb;//discuss里有人用的是axorb<span style="color: rgb(199, 37, 78); font-family: 'small Monaco', Menlo, Consolas, 'Courier New', monospace; line-height: 15.5844163894653px; background-color: rgb(249, 242, 244);"> &= -axorb,更巧妙</span> int a,b; a=b=0; for(int i=0;i<nums.size();i++){ if(lastbit&nums[i]) a^=nums[i]; else b^=nums[i]; } return vector<int> {a,b}; } };
相关文章推荐
- Xamarin.Android使用教程之Android项目结构
- 论坛中摘取的,关于Nor flash一些问题点
- Citrix的ICA协议介绍与对比
- 容器vector 的用法
- 解决eclipse+tomcat7的中文乱码的一个方法
- LeakCanary:简单粗暴的内存泄漏检测工具
- 转-用Eclipse 开发Dynamic Web Project应用程序
- Java编程机试:获取某一字符串中(只要字母),每一个字母出现的次数输出格式为a(x)b(y)c(z).....m(n)
- PHP图像处理--不超过给定大小的等比例的缩放
- 需要解决的问题ionic nvbar 和 view的分离
- 【leetcode】73. Set Matrix Zeroes
- Linux入门(一):50个最常用的指令
- 事件总结
- Android实现跑马灯效果的方法
- iOS中读取照片库
- outline轮廓线在不同CSS样式下的表现
- js追加元素,以及元素位置
- Linux 下网络性能优化方法简析
- Web性能优化系列
- jmeter测试TCP服务器/模拟发送TCP请求 设置16进制发送(转)