|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +/** |
| 5 | + * Given a non-empty array of integers, every element appears twice except for one. Find that single one. |
| 6 | + */ |
| 7 | +public class SingleNumber { |
| 8 | + public static void main(String[] args){ |
| 9 | + int[] nums = {4,1,2,1,2}; |
| 10 | + |
| 11 | + System.out.println("Single number is : " + singleNumber(nums)); |
| 12 | + |
| 13 | + //Improved solution - single pass |
| 14 | + System.out.println("Single number is : " + singleNumberInSinglePass(nums)); |
| 15 | + |
| 16 | + //Improved solution - Space complexity O(1) |
| 17 | + System.out.println("Single number is : " + singleNumberXOR(nums)); |
| 18 | + |
| 19 | + } |
| 20 | + |
| 21 | + public static int singleNumber(int[] nums) { |
| 22 | + Map<Integer,Integer> map = new HashMap<>(); |
| 23 | + for(int i=0; i < nums.length; i++){ |
| 24 | + if(map.get(nums[i])==null){ |
| 25 | + map.put(nums[i], 1); |
| 26 | + } else { |
| 27 | + map.put(nums[i], map.get(nums[i])+1); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + for(int key : map.keySet()){ |
| 32 | + if(map.get(key) == 1) return key; |
| 33 | + } |
| 34 | + |
| 35 | + return -1; |
| 36 | + } |
| 37 | + |
| 38 | + private static int singleNumberInSinglePass(int[] nums) { |
| 39 | + Map<Integer,Integer> map = new HashMap<>(); |
| 40 | + for(int i=0; i < nums.length; i++){ |
| 41 | + if(map.containsKey(nums[i])) map.remove(nums[i]); |
| 42 | + else map.put(nums[i], 1); |
| 43 | + } |
| 44 | + return map.keySet().iterator().next(); |
| 45 | + } |
| 46 | + |
| 47 | + public static int singleNumberXOR(int[] nums) { |
| 48 | + int num = 0; |
| 49 | + for (int x : nums) { |
| 50 | + num ^= x; |
| 51 | + System.out.println(num); |
| 52 | + } |
| 53 | + return num; |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments