[LintCode] 落单的数II Single Number II
2016-04-07 09:20
197 查看
给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字。
样例
给出 [1,2,2,3,4,4,5,3],返回 1和5
挑战
O(n)时间复杂度,O(1)的额外空间复杂度
Given 3*n + 1 numbers, every numbers occurs triple times except one, find it.
Example
Given [1,1,2,3,3,3,2,2,4,1] return 4
Challenge
One-pass, constant extra space.
思路:所有数字每一位之和模3
样例
给出 [1,2,2,3,4,4,5,3],返回 1和5
挑战
O(n)时间复杂度,O(1)的额外空间复杂度
Given 3*n + 1 numbers, every numbers occurs triple times except one, find it.
Example
Given [1,1,2,3,3,3,2,2,4,1] return 4
Challenge
One-pass, constant extra space.
思路:所有数字每一位之和模3
public class Solution { /** * @param A : An integer array * @return : An integer */ public int singleNumberII(int[] A) { int[] B = new int[32]; for(int j = 0; j < A.length; j++){ for(int i = 0; i < 32; i++) { if((1<<i & A[j]) == 1<<i) { B[i] = (B[i] + 1) % 3; } } } int result = 0; for(int i = 0; i < 32; i++) { result = 2 * result + B[31-i]; } return result; } }
相关文章推荐
- 第三次上机试验-1
- 3.1.10 错误处理
- Linux route命令
- UIWindow简单介绍
- Sort Colors(荷兰旗问题)
- c# 关于继承类中构造函数的实现
- Html - 涟漪特效
- 快速排序算法 原理及golang语言实现
- JVM内幕:Java虚拟机详解
- 并发模式(三)——生产者-消费模式
- c++作业3-多分数段函数求值、定期存款利息计算器、本月有几天?
- 第5周项目4长方柱类
- 3.1.8 面向对象编程
- 3.1.9 变长参数
- 安卓-屏幕适配的五种方式
- 第三周项目4(3)三色球问题
- C++实验3-个人所得税的计算
- Linux大杀器命令:查找所有目录下的所有文件的字符串命令
- centos ssh远程登陆
- .NET跨平台实践:用C#开发Linux守护进程-Daemon