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

  1. if they are equal, the counter + 1;
  2. 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;
  3. 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: 

  1. For each integer, it is represented by 32 bits, we count the number of "1"s for each i
  2. Do "module 3" operation and "or" operation to put it back to the result.
  3. Except the single value, other values occur three time, that means the bit should be zero if the count is moduled with 3.
  4. 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:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. 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.

  1. First, we do xor operations for all element in the array, the result is the xor of two number we want.
  2. 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
  1. 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的更多相关文章

  1. LeetCode Single Number I / II / III

    [1]LeetCode 136 Single Number 题意:奇数个数,其中除了一个数只出现一次外,其他数都是成对出现,比如1,2,2,3,3...,求出该单个数. 解法:容易想到异或的性质,两个 ...

  2. 【LeetCode】Single Number I & II & III

    Single Number I : Given an array of integers, every element appears twice except for one. Find that ...

  3. Leetcode 137. Single Number I/II/III

    Given an array of integers, every element appears twice except for one. Find that single one. 本题利用XO ...

  4. LeetCode 【Single Number I II III】

    Given an array of integers, every element appears twice except for one. Find that single one. 思路: 最经 ...

  5. 4.Single Number && Single Number (II)

    Single Number: 1. Given an array of integers, every element appears twice except for one. Find that ...

  6. LeetCode: Single Number I && II

    I title: Given an array of integers, every element appears twice except for one. Find that single on ...

  7. LeetCode Single Number I II Python

    Single Number Given an array of integers, every element appears twice except for one. Find that sing ...

  8. Single Number I&& II——还没看,倒过头来再看

    Single Number I Given an array of integers, every element appears twice except for one. Find that si ...

  9. leetcode 136. Single Number 、 137. Single Number II 、 260. Single Number III(剑指offer40 数组中只出现一次的数字)

    136. Single Number 除了一个数字,其他数字都出现了两遍. 用亦或解决,亦或的特点:1.相同的数结果为0,不同的数结果为1 2.与自己亦或为0,与0亦或为原来的数 class Solu ...

随机推荐

  1. ELK5.0安装教程

    ELK升级后,安装稍微发生了点变化,在Elasticsearch中增加了很多资源上的限制,其他的倒是没什么变化.不过所有的安装都是基于JDK已经安装完的情况,且为1.8版本. 安装Elasticsea ...

  2. 实现Unity编辑器模式下的旋转

    最近在做一个模型展示的项目,我的想法是根据滑动屏幕的x方向差值和Y方向的差值,来根据世界坐标下的X轴和Y轴进行旋转,但是实习时候总是有一些卡顿.在观察unity编辑器下的旋转之后,发现编辑器下的旋转非 ...

  3. Spring的IoC容器

    Spring是一个轻量级的Java开发框架,其提供的两大基础功能为IoC和AOP,其中IoC为依赖反转(Inversion of Control).IOC容器的基本理念就是"为别人服务&qu ...

  4. OpenStack_Glance

    什么是Glace Glance即image service(镜像服务),就是为创建虚拟机提供镜像的地方 为什么要有Glance 这个问题问的好,openstack就是构建Iaas平台对外提供虚拟机的啊 ...

  5. SVG动画-基础篇

    参考资料: http://www.w3school.com.cn/svg/index.asp https://msdn.microsoft.com/zh-cn/library/gg193979 简介 ...

  6. JAVA优化建议

    前言 代码优化,一个很重要的课题.可能有些人觉得没用,一些细小的地方有什么好修改的,改与不改对于代码的运行效率有什么影响呢?这个问题我是这么考虑的,就像大海里面的鲸鱼一样,它吃一条小虾米有用吗?没用, ...

  7. STM32驱动OV7725摄像头颜色识别

    实验目的: 使用stm32驱动OV7725摄像头进行图像实时采集,在tft屏幕上实时显示并识别图像中的特定颜色,在颜色的周围画上框. 实验现象: 我的工程代码链接: http://download.c ...

  8. 老李推荐:第8章6节《MonkeyRunner源码剖析》MonkeyRunner启动运行过程-启动Monkey 4

    在获得比对设备序列号后,findAttachedDevice就会跟提供的序列号进行比对,如果吻合就返回给调用者” 代码8-6-3 AdbBackend - waitForConnection”了.而A ...

  9. 老李推荐:第8章3节《MonkeyRunner源码剖析》MonkeyRunner启动运行过程-启动AndroidDebugBridge 3

    首先它通过查找JVM中的System Property来找到"com.android.monkeyrunner.bindir"这个属性的值,记得前面小节运行环境初始化的时候在mon ...

  10. 玩转 SSH(一):使用 Struts 搭建简单站点

    我们将使用 Struts 搭建一个简单的应用,当用户发送 HTTP 请求时,Action 类响应并设置返回信息,JSP 页面显示 Action 类中设置的信息. 首先,我们使用 Maven 的 mav ...