• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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?

Lintcode 也有这道题 Single Number III

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 }

 

posted @ 2015-12-23 05:43  neverlandly  阅读(232)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3