题目

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

代码

class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = ;
const int W = sizeof(int)*;
int *count = new int[W]();
for (size_t i = ; i < nums.size(); ++i)
{
for (size_t j = ; j < W; ++j)
{
count[j] += (nums[i] >> j) & ;
}
}
for (size_t i = ; i < W; ++i)
{
if ( count[i]%!= )
{
result += ( << i);
}
}
delete []count;
return result;
}
};

Tips:

1. 算法原理:由于都是int型的,只需要记录每个bit上1出现的次数;如果1出现的次数不是3的倍数,则将该位置置为1,并赋值到result中。

这道题主要是熟悉下位运算的各种操作,有时巧用位运算,可以大大提升代码效率。

================================================================

学习了另一种解法,代码如下:

class Solution {
public:
int singleNumber(vector<int>& nums) {
int one=, two=, three=;
for (size_t i = ; i < nums.size(); ++i)
{
two |= (one & nums[i]);
one ^= nums[i];
three = two & one;
one &= ~three;
two &= ~three;
}
return one;
}
};

参考链接:https://leetcode.com/discuss/857/constant-space-solution

简单说就是,用二进制模拟三进制运算。

循环体中的五条语句分别做了如下的事情:

1. 算上nums[i]之后,1出现了两次的bit位数有哪些

(包括两种情况:a.原来就是2次的,nums[i]在该bit上是0;原来是1次的,nums[i]在该bit上是1)。

2. 算上nums[i]之后,1出现了一次的bit位数有哪些。

3. 算上nums[i]之后,1出现了三次的bit位数有哪些

4和5. 满3进位,清空。

这里可能会有一个疑问:1出现次数为一和为二的能否算重了?

假设nums[i]在某一个bit上是0:

  a. 算two的时候,这一位不会影响原来two这一bit的取值。

  b. 算one的时候,相当于该bit与0异或,保持不变。

假设nums[i]在某一个bit上是1:

  a. 算two的时候,如果one在该bit上也是1,则two这一bit取1,如果one在这一位上是0,则two这一bit上不变。

  b. 算one的时候,相当于该bit与1异或,取反。如果one原来是1,则进位,one置为0;如果one原来是0,则变为1。

对比颜色相同的两端文字,可以知道是不会算重复的。

想到这里还有一个疑问:two = two | (one & nums[i]),如果某一bit上two原来就是1,并且还有进位了,那这?

这种case是不可能出现的:因为one two three初始都是0,假如连着三个nums[i]在某个bit上都为1,则three在该bit上就为1了。后面两条语句,就保证了two和one被清空了,因此永远不会出现two原来是1并且有进位的情况。

======================================================

第二次过这道题,想了一段时间。大体思路已经想出来了,但是位运算操作(“左移多少位再跟1进行与操作”这些的技巧)参考了书上的code。代码还是一次AC了。

class Solution {
public:
int singleNumber(vector<int>& nums) {
int int_bits = sizeof(int)*;
vector<int> count(int_bits,);
// count each '1' in each bit
for ( int i=; i<nums.size(); ++i )
{
for ( int j=; j<count.size(); ++j )
{
count[j] += (nums[i] >> j) & ;
count[j] = count[j] % ;
}
}
// extract single number
int single = ;
for ( int i=; i<count.size(); ++i )
{
single = single + ( count[i] << i );
}
return single;
}
};

还是这种思路好记一些,二进制代替三进制运算的那个并没有印象了。

【Single Num II】cpp的更多相关文章

  1. 【Word Break II】cpp

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  2. 【Unique Paths II】cpp

    题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. H ...

  3. 【Path Sum II】cpp

    题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...

  4. 【Spiral Matrix II】cpp

    题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. ...

  5. 【palindrome partitioning II】cpp

    题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...

  6. 【Jump Game II 】cpp

    题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...

  7. 【Combination Sum II 】cpp

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  8. 【Word Ladder II】cpp

    题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

  9. 【N-Quens II】cpp

    题目: Follow up for N-Queens problem. Now, instead outputting board configurations, return the total n ...

随机推荐

  1. Google常用拓展插件

    1.web前端助手(FEhelper)提供一些实用的前端小工具,功能十分贴心 2.bookMarks Manager 一个书签管理工具 3.Clear Cache 清除浏览器的缓存,有很多供选择的条目 ...

  2. Android仿微信高效压缩图片(libjpeg)

    用过ios手机的同学应该很明显感觉到,ios拍照1M的图片要比安卓拍照排出来的5M的图片还要清晰.这是为什么呢? 这得了解android底层是如何对图片进行处理的. 当时谷歌开发Android的时候, ...

  3. 网页游戏中PK系统的实现

    在游戏开发过程中,写过一个简单的PK系统面板,涉及到前端和后端的交互,我将自己制作的流程分享给大家,大概流程是这样:前端发送PK邀请给后端,后端受到请求后将信息返回给前端处理,先来看下整个流程图及思路 ...

  4. meterpreter > migrate 1548

    1548  1500  explorer.exe      x86   0           LIXIULI-VCS86VR\test      C:\WINDOWS\Explorer.EXE 19 ...

  5. java Vamei快速教程22 内存管理和垃圾回收

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 整个教程中已经不时的出现一些内存管理和垃圾回收的相关知识.这里进行一个小小的总结. ...

  6. ehcache常用API整理

    鉴于csdn的blog的不稳定, 及混乱的编辑器, 和无上传功能, 遂决定彻底投诚javaeye的blog. 数月前整理的一个东西, 作为cache的扫盲文档.参考了它的官方文档. 对ehcache感 ...

  7. 【洛谷5358】[SDOI2019] 快速查询(模拟)

    点此看题面 大致题意: 有单点赋值.全局加法.全局乘法.全局赋值.单点求值.全局求和\(6\)种操作.现在给出操作序列,以及\(t\)对正整数\(a_i,b_i\).让你处理\(t*q\)次操作,每次 ...

  8. Shuffle Cards

    C: Shuffle Cards 时间限制: 1 Sec  内存限制: 128 MB提交: 3  解决: 3[提交] [状态] [讨论版] [命题人:admin] 题目描述 Eddy likes to ...

  9. javaweb基础(29)_EL表达式

    一.EL表达式简介 EL 全名为Expression Language.EL主要作用: 1.获取数据 EL表达式主要用于替换JSP页面中的脚本表达式,以从各种类型的web域 中检索java对象.获取数 ...

  10. 【luogu P3608 [USACO17JAN]Balanced Photo平衡的照片】 题解

    题目链接:https://www.luogu.org/problemnew/show/P3608 乍一看很容易想到O(N^2)的暴力. 对于每个H[i]从i~i-1找L[i]再从i+1~n找R[i], ...