Leetcode – Single Number (Java)
The problem:
Given an array of integers, every element appears twice except for one. Find that single one.
Java Solution 1
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.
public int singleNumber(int[] A) { int x = 0; for (int a : A) { x = x ^ a; } return x; } |
Java Solution 2
public int singleNumber(int[] A) { HashSet<Integer> set = new HashSet<Integer>(); for (int n : A) { if (!set.add(n)) set.remove(n); } Iterator<Integer> it = set.iterator(); return it.next(); } |
The question now is do you know any other ways to do this?
<pre><code> String foo = "bar"; </code></pre>
-
Gaurav Dhimate
-
Milos Kosanovic
-
kkkkbbbb
-
Vipin Tiwari
-
fishwen
-
Adil qureshi
-
Peter
-
Adil qureshi
-
Frank
-
raman singh
-
nirvana_tan
-
象道