Single Number
2016-05-13 14:29
204 查看
1、Single Number I
2、Single Number II
int 共有32位,假设把所有的数相加,则并且每位上产生的进位不累计进入其他位:
因为一共只有一位个数为1,其他位个数都为3,则这些数相加,每位上累计个数取余3为0,或者1,最后把这位合并就是个数为1 的数。
这种做法可以通用,并且只用了两个变量。
3、Single Number III
class Solution { public: int singleNumber(vector<int>& nums) { if(nums.size()==0) return NULL; int res=nums[0]; for(int i=1;i<nums.size();i++) { res^=nums[i]; } return res; } };
2、Single Number II
int 共有32位,假设把所有的数相加,则并且每位上产生的进位不累计进入其他位:
因为一共只有一位个数为1,其他位个数都为3,则这些数相加,每位上累计个数取余3为0,或者1,最后把这位合并就是个数为1 的数。
这种做法可以通用,并且只用了两个变量。
class Solution { public: int singleNumber(vector<int>& nums) { int result = 0; int count =0 ; for(int i=0; i<32; i++) { count =0; for(int j=0; j<nums.size(); j++) count += (nums[j]>>i)&1; result |= (count%3)<<i; } return result; } };
3、Single Number III
class Solution { private: int last1(int n) { int i=0; while(((n>>i)&1) == 0) { i++; } return i; } bool isRange(int n, int i) { if(((n>>i)&1) ==1) return true; else return false; } public: vector<int> singleNumber(vector<int>& nums) { vector<int> res; if(nums.size()<2) return res; int num = 0; for(int i=0; i<nums.size(); ++i) { num = num^nums[i]; } int n = last1(num); int a=0, b=0; for(int j=0; j<nums.size(); ++j) { if(isRange(nums[j], n)) { a = a^nums[j]; } else { b = b^nums[j]; } } res.push_back(a); res.push_back(b); return res; } };
相关文章推荐
- Linux 操作MySQL常用命令行
- php 开发移动应用接口
- 启动Tomcat,出现source not found...
- 【基础】Oracle 表空间和数据文件
- CodeForces 599B Spongebob and Joke
- javaScript和H5开发神器之WebStrom
- Laravel的DB类在哪
- Stanford CoreNLP--Split Sentence
- 获取 request 中 json 数据
- 好好和h5沟通!几种常见的hybrid通信方式
- (OK) dnf - yum - Installing Free and Nonfree Repositories
- 表空间与数据文件
- C#反射机制来获取类 属性的描述
- This version of the rendering library is more recent than your version of ADT plug-in. Please update
- 解决mariadb识别字母大小敏感问题
- dhtmlxTree介绍
- eclipse图库
- 基于二进制程序的类型推导--TIE: Principled Reverse Engineering of Types in Binary Programs
- 使用merge subView优化布局
- 线性链表 (1)