[LeetCode#260]Single Number III
Problem:
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Analysis:
Sort a array is always a good beginning to find duplciates in a array.
But it would at least take O(nlogn) time in sorting the array. Solution 1:
Basic idea:
step 1: sort the entire array.
step 2: in the sorted form, if a element does not have neighors share the same value wit it. It must be the single element we want to find.
Note: take care the first and last element, it may incure out of bound exception. public int[] singleNumber(int[] nums) {
if (nums == null || nums.length <= 1)
return new int[0];
Arrays.sort(nums);
int[] ret = new int[2];
int count = 0;
for (int i = 0; i < nums.length; i++) {
boolean is_single = true;
if (i != 0)
is_single = is_single && (nums[i] != nums[i-1]);
if (i != nums.length - 1)
is_single = is_single && (nums[i] != nums[i+1]);
if (is_single)
ret[count++] = nums[i];
}
return ret;
} Wrong logic:
If you use the default value of flag as "true", you must take care the logic you are going to implment. (|| or &&)
Initially, I have implemented following problemetic logic
-------------------------------------------------------------------
for (int i = 0; i < nums.length; i++) {
boolean is_single = true;
if (i != 0)
is_single = is_single || (nums[i] != nums[i-1]);
if (i != nums.length - 1)
is_single = is_single || (nums[i] != nums[i+1]);
if (is_single) {
ret[count] = nums[i];
count++;
}
}
------------------------------------------------------------------- In the above code, the is_single would alway be true, since the intial default is true and I use "||" to pass around logic.
What I meant to do is "once it has a neighor, it should return false, and pass to the value".
The change is easy:
is_single = is_single && (nums[i] != nums[i-1]); Even though the above solution is clear, there could a very elegant and genius solution for this problem.
But it requires strong understand of bit operation.
Key:
The magic rule of XOR.
a ^ a = 0;
a ^ b ^ a = 0;
a ^ b ^ c ^ a = b ^ c;
After the XOR operation, all numbers appear even times, would be removed from the final XOR value.
What's more, after "a ^ b ^ c ^ a = b ^ c", the set bits of "b ^ c" would only contain the digits that b are different from c. Solving step:
step 1: XOR all elements in the array. int xor = 0;
for (int i = 0; i < nums.length; i++) {
xor ^= nums[i];
} step 2: get the rightmost bit of the set bit.
right_most_bit = xor & (~(xor-1)); step 3: divide the nums array into two set based on the set bit. (thus the single numbers: b, c would be placed into two different set). Then XOR at each set and get those two numbers.
for (int i = 0; i < nums.length; i++) {
if ((nums[i] & right_most_bit) == 0) {
ret[0] ^= nums[i];
} else{
ret[1] ^= nums[i];
}
} Skills:
1. how to get the rightmost set bit?
right_most_bit = xor & (~(xor-1));
Reason:
The xor-1 would turn the rightmost set bit into 0, and bits after it becomes 1.
'1000001000' => '1000000111'
The not "~" operation would turn all bits into opposite bit (note the rightmost bitset has already been setted into 0)
'1000000111' => '0111111000'
The '&' operation would filter the setbit out.
'0111111000'
'1000001000'
'0000001000' 2. The set bit could be used a proper indicator to divide the original array into two sets.
if ((nums[i] & right_most_bit) == 0) {
ret[0] ^= nums[i];
} else{
ret[1] ^= nums[i];
}
Note the form of set bit: '0000001000', only the number share the same bit would not equal to "000000000...(integer: 0)"
Solution:
public class Solution {
public int[] singleNumber(int[] nums) {
if (nums == null || nums.length == 0)
return new int[0];
int[] ret = new int[2];
int xor = 0, right_most_bit = 0;
for (int i = 0; i < nums.length; i++) {
xor ^= nums[i];
}
right_most_bit = xor & (~(xor-1));
for (int i = 0; i < nums.length; i++) {
if ((nums[i] & right_most_bit) == 0) {
ret[0] ^= nums[i];
} else{
ret[1] ^= nums[i];
}
}
return ret;
}
}
[LeetCode#260]Single Number III的更多相关文章
- LeetCode 260. Single Number III(只出现一次的数字 III)
LeetCode 260. Single Number III(只出现一次的数字 III)
- [LeetCode] 260. Single Number III 单独数 III
Given an array of numbers nums, in which exactly two elements appear only once and all the other ele ...
- Java [Leetcode 260]Single Number III
题目描述: Given an array of numbers nums, in which exactly two elements appear only once and all the oth ...
- LeetCode 260 Single Number III 数组中除了两个数外,其他的数都出现了两次,找出这两个只出现一次的数
Given an array of numbers nums, in which exactly two elements appear only once and all the other ele ...
- Leetcode 260 Single Number III 亦或
在一个数组中找出两个不同的仅出现一次的数(其他数字出现两次) 同样用亦或来解决(参考编程之美的1.5) 先去取出总亦或值 然后分类,在最后一位出现1的数位上分类成 ans[0]和ans[1] a&am ...
- [LeetCode] 260. Single Number III(位操作)
传送门 Description Given an array of numbers nums, in which exactly two elements appear only once and a ...
- leetcode 136 Single Number, 260 Single Number III
leetcode 136. Single Number Given an array of integers, every element appears twice except for one. ...
- leetcode 136. Single Number 、 137. Single Number II 、 260. Single Number III(剑指offer40 数组中只出现一次的数字)
136. Single Number 除了一个数字,其他数字都出现了两遍. 用亦或解决,亦或的特点:1.相同的数结果为0,不同的数结果为1 2.与自己亦或为0,与0亦或为原来的数 class Solu ...
- 【刷题-LeeetCode】260. Single Number III
Single Number III Given an array of numbers nums, in which exactly two elements appear only once and ...
随机推荐
- python 面向对象简单理解
面向对象: 是一种程序设计范型 作用: 提高软件的重用性和灵活性,扩展性 世界万物一切皆为对象,对象即是指由特定状态,特征,行为的实体 知识点一: 代码的重用 举个栗子 比如小月月有了一个女朋友1 ...
- JVM Davilk ART 简介 区别
JVM和DVM JavaSE 程序使用的虚拟机叫 Java Virtual Machine,简称 JVM.Android 平台虽然是使用java语言来开发应用程序,但Android程序却不是运行在标准 ...
- ThinkPHP的数据库访问的简单操作
传统的sql与ThinkPHP中的sql相比较 以user表为例 $user=M('user'); 1: SELECT * FROM user----------$user->select( ...
- jquery ajax获取和解析数据
最近项目中用到了ajax技术,之前虽然写过一点点,但是没有系统的总结过.趁着刚刚用过,手热就记录一下,方便以后查阅. $.ajax中的参数 $.ajax的函数格式: $.ajax({ type: 'P ...
- java 执行sql脚本的3种方式 (ant,ibatis,ScriptRunner)
package com.unmi; import java.io.*; import org.apache.tools.ant.*; import org.apache.tools.ant.taskd ...
- Sqlserver 列转行 行转列
sqlserver的行转列 列转行问题 行转列:1 使用Case when 方式 CREATE TABLE [StudentScores]( [UserName] NVARCHAR(20), --学生 ...
- Linux下追踪函数调用,打印栈帧
事情的起因是这样的,之前同事的代码有一个内存池出现了没有回收的情况.也就是是Pop出来的对象没有Push回去,情况很难复现,所以在Pop里的打印日志,跟踪是谁调用了它,我想在GDB调试里可以追踪调用的 ...
- c++primerplus(第六版)编程题——第4章(复合类型)
声明:作者为了调试方便,每一章的程序写在一个工程文件中,每一道编程练习题新建一个独立文件,在主函数中调用,我建议同我一样的初学者可以采用这种方式,调试起来会比较方便. (具体方式参见第3章模板) 1. ...
- demo_04绘制三角形
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- sass用法
可能刚开始我们学习前端的时候都习惯用html+css.来做网页,但是我们发现css有很多重复的代码或者是你要改里面的图片或者文字还有去诶个的找很麻烦,所以我们就用sass来简化它. 首先我们需要安装一 ...