136. Single Number
Easy
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
package leetcode.easy; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class SingleNumber { @org.junit.Test public void test() { int[] nums1 = { 2, 2, 1 }; int[] nums2 = { 4, 1, 2, 1, 2 }; System.out.println(singleNumber1(nums1)); System.out.println(singleNumber1(nums2)); System.out.println(singleNumber2(nums1)); System.out.println(singleNumber2(nums2)); System.out.println(singleNumber3(nums1)); System.out.println(singleNumber3(nums2)); System.out.println(singleNumber4(nums1)); System.out.println(singleNumber4(nums2)); } public int singleNumber1(int[] nums) { HashSet<Integer> set = new HashSet<Integer>(); int result = 0; for (int i = 0; i < nums.length; i++) { if (!set.contains(nums[i])) { set.add(nums[i]); } else { set.remove(nums[i]); } } Iterator<Integer> it = set.iterator(); while (it.hasNext()) { result = it.next(); } return result; } public int singleNumber2(int[] nums) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int result = 0; for (int i = 0; i < nums.length; i++) { if (!map.containsKey(nums[i])) { map.put(nums[i], 1); } else { map.remove(nums[i]); } } Set<Integer> set = map.keySet(); Iterator<Integer> it = set.iterator(); while (it.hasNext()) { result = it.next(); } return result; } public int singleNumber3(int[] nums) { HashSet<Integer> set = new HashSet<Integer>(); int sumSet = 0; int sum = 0; for (int i = 0; i < nums.length; i++) { set.add(nums[i]); sum += nums[i]; } Iterator<Integer> it = set.iterator(); while (it.hasNext()) { sumSet += it.next(); } return 2 * sumSet - sum; } public int singleNumber4(int[] nums) { int a = 0; for (int i = 0; i < nums.length; i++) { a ^= nums[i]; } return a; } }