LeetCode_136. Single Number

 

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 set = new HashSet();
		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 it = set.iterator();
		while (it.hasNext()) {
			result = it.next();
		}
		return result;
	}

	public int singleNumber2(int[] nums) {
		HashMap map = new HashMap();
		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 set = map.keySet();
		Iterator it = set.iterator();
		while (it.hasNext()) {
			result = it.next();
		}
		return result;
	}

	public int singleNumber3(int[] nums) {
		HashSet set = new HashSet();
		int sumSet = 0;
		int sum = 0;
		for (int i = 0; i < nums.length; i++) {
			set.add(nums[i]);
			sum += nums[i];
		}
		Iterator 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;
	}
}

 

你可能感兴趣的:(LeetCode_136. Single Number)