zoukankan      html  css  js  c++  java
  • Single Number 解答

    Question

    Given an array of integers, every element appears twice except for one. Find that single one.

    Solution 1 -- Set

    We can use a hash set to record each integer's appearing time. Time complexity O(n), space cost O(n)

     1 public class Solution {
     2     public int singleNumber(int[] nums) {
     3         Set<Integer> counts = new HashSet<Integer>();
     4         int length = nums.length, result = nums[0];
     5         for (int i = 0; i < length; i++) {
     6             int tmp = nums[i];
     7             if (counts.contains(tmp))
     8                 counts.remove(tmp);
     9             else
    10                 counts.add(tmp);
    11         }
    12         for (int tmp : counts)
    13             result = tmp;
    14         return result;
    15     }
    16 }

    Solution 2 -- Bit Manipulation

    The key to solve this problem is bit manipulation. XOR will return 1 only on two different bits. So if two numbers are the same, XOR will return 0. Finally only one number left.

    1 public int singleNumber(int[] A) {
    2     int x = 0;
    3     for (int a : A) {
    4         x = x ^ a;
    5     }
    6     return x;
    7 }
  • 相关阅读:
    Shell编程常用
    毕设问答
    《如何高效学习》
    《如何阅读一本书》(未完)
    《牧羊少年奇幻之旅》
    2019.04月总结
    上周还是合意的,且找到了一定的遵循4.6-4.12

    错误和异常
    数据结构
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4809029.html
Copyright © 2011-2022 走看看