博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Single Number III
阅读量:7097 次
发布时间:2019-06-28

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

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?

Lintcode 也有这道题

example:

1 0 1 0 0 0

1 0 1 0 0 0

0 0 1 0 0 0

0 0 1 0 0 0

1 0 0 1 0 0

1 0 0 1 0 0

0 0 1 0 0 0

0 0 1 0 0 1

如例所示,最后两个数8,9即是所求Single Number, 即使它们能使某一位上的1凑成偶数(使得Single Number I 的方法不再有效)如上例从右到左第4位,但是始终会至少有某一位的1仍是奇数(如上例从右到左第一位)。

想法就是把这些数分成两拨,让这两个single number各在一拨,然后各自按Single Number I 的做法做,就可以找出来

取上述为1的各位中某一位,方便起见取最右边为1的那位,所有那位为1的数形成一拨,其余数形成另一拨,这样就把两个数分开到两拨了。各自XOR就可以得到两个数。

取最右边为1的那位的方法是:n & (-n)

Single Number I的一个简便方法是XOR各个数,如果某一位的1的个数是奇数,XOR之后仍将为1.

1 public class Solution { 2     public int[] singleNumber(int[] nums) { 3         int[] res = new int[2]; 4         int n = 0; 5         for (int elem : nums) { 6             n ^= elem; 7         } 8         n = n & (-n); 9         for (int elem : nums) {10             if ((n & elem) == n) {11                 res[0] ^= elem;12             }13             else res[1] ^= elem;14         }15         return res;16     }17 }

 

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

你可能感兴趣的文章
gitlab项目数据同步
查看>>
关于Service与Broadcast以及Notification的终于告一段落了
查看>>
VO,PO,POJO的定义和区别
查看>>
Python环境搭建
查看>>
瑞信CDP与HA集群
查看>>
RAID各级别的特性
查看>>
Python学习笔记__7.3章 多重继承
查看>>
爱创课堂每日一题七十天- 说说你对前端架构师的理解?
查看>>
兄弟连第7节课
查看>>
学习笔记(11月15日)
查看>>
JavaWeb21-HTML篇笔记
查看>>
Java之品优购部署_day03(3)
查看>>
前端与移动开发之vue-day4(2)
查看>>
phpcms筛选功能
查看>>
简练软考知识点整理-制定进度计划过程
查看>>
26 LAMP
查看>>
Oracle解决用户锁的问题
查看>>
深入了解Kafka基本原理
查看>>
springCloud分布式事务实战(六)编写第二个微服务
查看>>
spark的HA集群搭建
查看>>