【问题标题】:The best way to find the single number in pairs or triples找到成对或成对的单个数字的最佳方法
【发布时间】:2016-04-26 17:43:12
【问题描述】:

因为这是一系列问题中的一个问题。我正在修改它以使其不与其他重复。感谢大家的帮助。

:我有一个整数数组。在数组中,每个元素都出现两次,除了一个。我想找到那个单一的号码。

例如:[2, 4, 2, 1, 4, 1, 3],单号为3

我的想法是使用HashMap,这需要O(n) 时间和O(n) 空间。有没有更好的解决方案?谢谢。

Triples:每个元素出现三次,除了一次。找到那个。

例如:[1, 2, 4, 2, 4, 1, 2, 4, 1, 3],单号为3

【问题讨论】:

标签: algorithm


【解决方案1】:

考虑用“位”的方式解决它,这需要O(n)时间和O(1)空间:

public class Solution {
    public int singleNumber(int[] A) {
        if (A.length==0) return 0;
        if (A.length==1) return A[0];

        int result = A[0];

        for (int i=1; i<A.length; i++) {
            result = result ^ A[i];
        }

        return result;         
    }
}

嗯,是的,我也有在三元组中找到单个的解决方案。

public class Solution {
    public int singleNumber(int[] A) {
        int result = 0;

        for (int i = 0; i < 32; i++) {
            int curr = 0;
            for (int num : A) {
                curr += (num >> i) & 1;
            }
            result += (curr % 3) << i;
        }

        return result;
    }
}

这对您来说可能更难理解。请阅读一些关于位操作的资料,然后弄清楚这个解决方案是如何工作的。

【讨论】:

  • 有趣,是来自“Hackers Delight”
  • 感谢您的及时回复。什么是“^”?
  • @AlexWien 之前刚解决过这个问题。当我看到这个位操作解决方案时,我什至感到震惊。
  • @Learner 谢谢。我会用谷歌搜索并了解更多相关信息。
猜你喜欢
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
相关资源
最近更新 更多