leetcode260-single number iii
来源:互联网 发布:单片机简易密码锁 编辑:程序博客网 时间:2024/06/05 08:28
题目:
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?
public class Solution { public int[] singleNumber(int[] nums) { if (nums==null || nums.length==0) return new int[]{}; if(nums.length==1) return new int[]{ nums[0] }; // get the xor result of the two single numbers int xor = 0; for (int num : nums) xor ^= num; // divide the numbers into two groups, get the mask to calculate which group will each number be put in int mask = 0; if (xor==0) { return new int[]{}; } else if (xor>0) { for (int i=1; i<32; i++) { int remainder = xor%2; if (remainder>0) { mask = 1 << (i-1); break; } xor = xor/2; } } else { mask = Integer.MIN_VALUE; } // num1 is the xor result for group 1, and num2 is for group2 int num1 = 0; int num2 = 0; for (int num : nums) { int group = num & mask; if (group==0) num1 ^= num; else num2 ^= num; } return new int[]{num1, num2}; }}
0 0
- Leetcode260 Single Number III
- leetcode260-single number iii
- leetcode260. Single Number III
- leetcode260. Single Number III
- leetcode260 Single Number III java
- LeetCode260——Single Number III精彩解法
- Single Number III
- Single Number III
- [LeetCode] Single Number III
- [leetcode] Single Number III
- 260 Single Number III
- [Leetcode]Single Number III
- [leetcode] Single Number III
- Leetcode: Single Number III
- 260 Single Number III
- LeetCode || Single Number III
- Single Number III
- Single Number III
- 【 MVC 】显示数据库数据表格
- 操作符重载及友元函数
- 调用第三方api之图灵机器人
- C++ ->重载
- 游戏类型
- leetcode260-single number iii
- Logistic回归总结
- Scrum 之 检查单
- 为什么python
- 二分法
- ajax解析xml和json文件的具体实现
- Redis Cluster Specification
- 接触chisel
- 抓到一只苍蝇!