博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 137:Single Number II
阅读量:4150 次
发布时间:2019-05-25

本文共 1129 字,大约阅读时间需要 3 分钟。

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?

Single Number II 比Single Number要复杂的多,很难直观的找到算法。

考虑每个元素的为一个32位的二进制数,这样每一位上出现要么为1 ,要么为0。对数组,统计每一位上1 出现的次数count,必定是3N或者3N+1 次。让count对3取模,能够获得到那个只出现1次的元素该位是0还是1。

代码如下:

class Solution {public:    int singleNumber(vector
& nums) { int length = nums.size(); int result = 0; for(int i = 0; i<32; i++){ int count = 0; int mask = 1<< i; for(int j=0; j
该方法同样适用于Single Number I的解答。
class Solution {public:    int singleNumber(vector
& nums) { int length = nums.size(); int result = 0; for(int i = 0; i<32; i++){ int count = 0; int mask = 1<< i; for(int j=0; j

对于Single Number II,网上还有一种与、异或等位操作的解法,尚未完全理解,先记录下

int singleNumber(int A[], int n){	int one = 0, two = 0;	for (int i = 0; i < n; i++)	{		two |= A[i] & one;		one ^= A[i];		int three = one & two;		one &= ~three;		two &= ~three;	}	return one;}

转载地址:http://kbxti.baihongyu.com/

你可能感兴趣的文章
基于S5PV210的uboot移植中遇到的若干问题记录(一)DM9000网卡移植
查看>>
Openwrt源码下载与编译
查看>>
我和ip_conntrack不得不说的一些事
查看>>
Linux 查看端口使用情况
查看>>
文件隐藏
查看>>
两个linux内核rootkit--之二:adore-ng
查看>>
两个linux内核rootkit--之一:enyelkm
查看>>
关于linux栈的一个深层次的问题
查看>>
rootkit related
查看>>
配置文件的重要性------轻化操作
查看>>
又是缓存惹的祸!!!
查看>>
为什么要实现程序指令和程序数据的分离?
查看>>
我对C++ string和length方法的一个长期误解------从protobuf序列化说起(没处理好会引起数据丢失、反序列化失败哦!)
查看>>
一起来看看protobuf中容易引起bug的一个细节
查看>>
无protobuf协议情况下的反序列化------貌似无解, 其实有解!
查看>>
make -n(仅列出命令, 但不会执行)用于调试makefile
查看>>
makefile中“-“符号的使用
查看>>
go语言如何从终端逐行读取数据?------用bufio包
查看>>
go的值类型和引用类型------重要的概念
查看>>
求二叉树中结点的最大值(所有结点的值都是正整数)
查看>>