|
| 1 | +packagemedium; |
| 2 | + |
| 3 | +importjava.util.HashSet; |
| 4 | +importjava.util.Iterator; |
| 5 | +importjava.util.Set; |
| 6 | + |
| 7 | +/**136. Single Number QuestionEditorial Solution My Submissions |
| 8 | +Total Accepted: 141879 |
| 9 | +Total Submissions: 277792 |
| 10 | +Difficulty: Medium |
| 11 | +Given an array of integers, every element appears twice except for one. Find that single one. |
| 12 | +
|
| 13 | +Note: |
| 14 | +Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? |
| 15 | +
|
| 16 | +Hide Company Tags Palantir Airbnb |
| 17 | +Hide Tags Hash Table Bit Manipulation |
| 18 | +Hide Similar Problems (M) Single Number II (M) Single Number III (M) Missing Number (H) Find the Duplicate Number |
| 19 | +*/ |
| 20 | +publicclassSingleNumber { |
| 21 | +//approach 1: use set, since this problem explicitly states that every element appears twice and only one appears once |
| 22 | +//so, we could safely remove the ones that are already in the set, O(n) time and O(n) space. |
| 23 | +//HashTable approach works similarly like this one, but it could be more easily extend to follow-up questions. |
| 24 | +publicintsingleNumber_using_set(int[]nums) { |
| 25 | +Set<Integer>set =newHashSet(); |
| 26 | +for(inti :nums){ |
| 27 | +if(!set.add(i))set.remove(i); |
| 28 | + } |
| 29 | +Iterator<Integer>it =set.iterator(); |
| 30 | +returnit.next(); |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | +//approach 2: bit manipulation, use exclusive or ^ to solve this problem: |
| 35 | +//we're using the trick here: every number ^ itself will become zero, so, the only remaining element will be the one that |
| 36 | +//appeared only once. |
| 37 | +publicintsingleNumber_using_bit(int[]nums) { |
| 38 | +intres =0; |
| 39 | +for(inti :nums){ |
| 40 | +res ^=i; |
| 41 | + } |
| 42 | +returnres; |
| 43 | + } |
| 44 | + |
| 45 | +} |