No so good solution in Java

  • 1

    I can only solve the problem using the following method (I DO know it doesn't comply to Could you implement it without using extra memory?).

    public int singleNumber(int[] nums) {
    	Map<Integer, Boolean> appeared = new HashMap<Integer, Boolean>();
    	for (int num : nums)
    		if (appeared.containsKey(num))
    			appeared.put(num, true);
    	return appeared.keySet().iterator().next();

    And I am interested in the solution post here . For convenient the code is:

    public int singleNumber(int[] nums) {
        if(nums.length == 1) {
            return nums[0];
        for(int i = 1; i < nums.length; i++) {
            nums[0] ^= nums[i]; 
        return nums[0]; 

  • 0

    Brilliance. For second solution code, XOR is the best answer, and the linear run time.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.