single number i && ii && iii
Problem statement
Elementary knowledge:
There is a popular question when I seeked my job at Beijing: swap the value of two numbers without allocate a new memory.
Normally, there are two solutions:
1 int main(){
2 int a = 3;
3 int b = 5;
4
5 a += b;
6 b = a - b;
7 a = a - b;
8
9 a ^= b;
10 b ^= a;
11 a ^= b;
12
13 return 0;
14 }
Some tricky:
x&(x-1): eliminate the last 1 bit in x
We can use this tricky to test if an integer is the power of 2 in O(1) time;
class Solution {
public:
/*
* @param n: An integer
* @return: True or false
*/
bool checkPowerOf2(int n) {
// write your code here
return n > && (n & (n - )) == ;
}
};
Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Solution one:
For this problem, we should use the knowledge that the XOR operation for two same number will be zero.
class Solution {
public:
int singleNumber(vector<int>& nums) {
int single_val = ;
for(vector<int>::size_type ix = ; ix < nums.size(); ix++){
single_val ^= nums[ix];
}
return single_val;
}
};
Solution two:
Since the array is random, the first action is to sort the array from small to large.
I keep a counter to count the number of current value. The loop ends at the element before the last one since we will compare current element with it`s direct next one. Because of this, we need do some boundary check to make sure there is at least one element in this array
- if they are equal, the counter + 1;
- if they are not equal:
- if the counter is 2, that means current is already end in the array, we need precede to it`s next one, the counter should start from 1 again.
- if the counter is less than 2( it should be 1), that means current only show up once, it is the single we want. return;
- If the function does not return in the while loop, that means the last element is the single value, we return nums.back();
class Solution {
public:
int singleNumber(vector<int>& nums) {
if(nums.empty()){
return ;
}
if(nums.size() == ){
return nums[];
}
sort(nums.begin(), nums.end());
int cnt = ;
for(vector<int>::size_type ix = ; ix < nums.size() - ; ix++){
if(nums[ix] == nums[ix + ]){
cnt++;
} else {
if(cnt < ){
return nums[ix];
} else {
cnt = ;
}
}
}
return nums.back();
}
};
Single Number ii
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Solution one:
Frist solutiuon is the same with singlue number i, we just need change the value of cnt to be 3, it will works.
class Solution {
public:
int singleNumber(vector<int>& nums) {
if (nums.size() == ) {
return nums[];
}
sort(nums.begin(), nums.end());
int cnt = ;
for (vector<int>::size_type ix = ; ix < nums.size(); ix++) {
if (nums[ix] == nums[ix + ]) {
cnt++;
} else {
if (cnt < ) {
return nums[ix];
} else {
cnt = ;
}
}
}
return nums.back();
}
};
Solution two:
- For each integer, it is represented by 32 bits, we count the number of "1"s for each i
- Do "module 3" operation and "or" operation to put it back to the result.
- Except the single value, other values occur three time, that means the bit should be zero if the count is moduled with 3.
- We will get the value of single number.
class Solution {
public:
int singleNumber(vector<int>& nums) {
int single_val = ;
int bit_sum = ;
for(int i = ; i < ; i++){
bit_sum = ;
for(vector<int>::size_type ix = ; ix < nums.size(); ix++){
bit_sum += (nums[ix] >> i) & ;
}
single_val |= (bit_sum % ) << i;
}
return single_val;
}
};
Solution three:
- ones: means the value when ith bit only occurs once
- twos: means the value when ith bit only occurs twice
- three: measn the value when ith bit only occurs third
class Solution {
public:
int singleNumber(vector<int>& nums) {
int one = , two = , three = ;
for (int i = ; i < nums.size(); ++i) {
two |= one & nums[i];
one ^= nums[i];
three = one & two;
one &= ~three;
two &= ~three;
}
return one;
}
};
Single number iii
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?
The rules for xor operation:
0: two bits are same
1: two bits are different
The xor operation is similiar with an addition without carry.
Solution:
There are two numbers only occur once, which is different with single number i. We can solve it with the single number i, however, we need do some precess before it.
- First, we do xor operations for all element in the array, the result is the xor of two number we want.
- Second, we should find one bit which is different in these two numbers and use this bit as an indicator to different them in next loop
- The bit representation of a negative number is: reverse all bits of its positive number and plus one
- Third, loop all elements in array to do xor operation and get the answer.
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int xor_of_two_numbers = ;
for(vector<int>::size_type ix = ; ix < nums.size(); ix++){
// this is the result of the xor of two single numbers
xor_of_two_numbers ^= nums[ix];
}
// the negative bit representation of each number
// reverse all bits and plus one
// find one bit from the xor result which this two single numbers is different
// different them in next loop
int right_most_bit_of_xor = xor_of_two_numbers & -xor_of_two_numbers;
vector<int> singleNumber();
for(vector<int>::size_type ix = ; ix < nums.size(); ix++){
if(nums[ix] & right_most_bit_of_xor){
singleNumber[] ^= nums[ix];
} else {
singleNumber[] ^= nums[ix];
}
}
return singleNumber;
}
};
single number i && ii && iii的更多相关文章
- LeetCode Single Number I / II / III
[1]LeetCode 136 Single Number 题意:奇数个数,其中除了一个数只出现一次外,其他数都是成对出现,比如1,2,2,3,3...,求出该单个数. 解法:容易想到异或的性质,两个 ...
- 【LeetCode】Single Number I & II & III
Single Number I : Given an array of integers, every element appears twice except for one. Find that ...
- Leetcode 137. Single Number I/II/III
Given an array of integers, every element appears twice except for one. Find that single one. 本题利用XO ...
- LeetCode 【Single Number I II III】
Given an array of integers, every element appears twice except for one. Find that single one. 思路: 最经 ...
- 4.Single Number && Single Number (II)
Single Number: 1. Given an array of integers, every element appears twice except for one. Find that ...
- LeetCode: Single Number I && II
I title: Given an array of integers, every element appears twice except for one. Find that single on ...
- LeetCode Single Number I II Python
Single Number Given an array of integers, every element appears twice except for one. Find that sing ...
- Single Number I&& II——还没看,倒过头来再看
Single Number I Given an array of integers, every element appears twice except for one. Find that si ...
- leetcode 136. Single Number 、 137. Single Number II 、 260. Single Number III(剑指offer40 数组中只出现一次的数字)
136. Single Number 除了一个数字,其他数字都出现了两遍. 用亦或解决,亦或的特点:1.相同的数结果为0,不同的数结果为1 2.与自己亦或为0,与0亦或为原来的数 class Solu ...
随机推荐
- 对VC++6.0爱得深沉(二)个性工具的定制
初始界面看起来很简洁,但是经过一番改造后,你会拥有私人定制的壮丽界面O(∩_∩)O~,让我们开始吧. 1)原有工具的显示隐藏.位置调整: 比如你觉得这个插入图标没什么用,想把这个隐藏,那么你可以打开[ ...
- Android 7.0 调取系统相机崩溃解决android.os.FileUriExposedException
一.写在前面 最近由于廖子尧忙于自己公司的事情和OkGo(一款专注于让网络请求更简单的网络框架) ,故让LZ 接替维护ImagePicker(一款支持单.多选.旋转和裁剪的图片选择器),也是处理了诸多 ...
- C# const和readonly修饰符的区别
const 的概念就是一个包含不能修改的值的变量.常数表达式是在编译时可被完全计算的表达式.因此不能从一个变量中提取的值来初始化常量.如果 const int a = b+1;b是一个变量,显然不能再 ...
- webService常见问题
1.普通字符串(日期形式)转换为XMLGregorianCalendar SimpleDateFormat simpleDateFormat =new SimpleDateFormat("y ...
- 使用Python对Excel进行读写操作
学习Python的过程中,我们会遇到Excel的读写问题.这时,我们可以使用xlwt模块将数据写入Excel表格中,使用xlrd模块从Excel中读取数据.下面我们介绍如何实现使用Python对Exc ...
- Unity - 通过降低精度减少动画文件的大小
Animation是Unity中的动画文件,主要内容由一个个关键帧数据构成.通过将Unity的资源序列化方式调整为Text,就可以以文本方式查看动画文件.通过菜单项Edit -> Project ...
- GitHub 添加 SSH keys
首先在本地创建 SSH Keys $ ssh-keygen -t rsa -C "18817801185@163.com" 后面的邮箱即为 github 注册邮箱,之后会要求确认路 ...
- 【转】一个工具类(可以控制多层嵌套的movieClip)
好多人也应该遇到和我一样的问题,当设计师给了我们一个多层嵌套的movieClip时,我们在写代码时无法将movieClip完全停止掉,主要是基于好多movieClip有深层嵌套,主时间轴不在最上层导致 ...
- AngularJS1.X学习笔记6-控制器和作用域
经过一番艰苦卓绝的鏖战,我终于来到了控制器和作用域部分.控制器作为MVC的C,其重要性不可谓不重要:作用域决定了你可以拿到哪些东西,亦是分外重要.现在就来学习一下两个东西.去看看$apply,$wat ...
- 深度学习实践系列(3)- 使用Keras搭建notMNIST的神经网络
前期回顾: 深度学习实践系列(1)- 从零搭建notMNIST逻辑回归模型 深度学习实践系列(2)- 搭建notMNIST的深度神经网络 在第二篇系列中,我们使用了TensorFlow搭建了第一个深度 ...