leetcode解题之136 #Single Number Java版(只出现一次的数字)

136. Single Number

Given an array of integers, every element appearstwice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

只出现一次的数字,其他全部两次,能不使用额外的空间吗?

使用map:

public  int singleNumber(int[] nums) {
		int i = 0;
		int j = nums.length - 1;
		Map map = new HashMap<>();
		while (i <= j) {
			if (map.containsKey(nums[i]))
				map.put(nums[i], map.get(nums[i])+1);
			else
				map.put(nums[i], 1);
			i++;
			
		}
		i = 0;
		while (i <= j) {
			if (map.get(nums[i]) == 1)
				break;
			i++;
		}
		return nums[i];
	}

使用异或运算:

如果a、b两个值不相同,则异或结果为1。如果a、b两个值相同,异或结果为0。

0与任何数做异或都是 那个数,相同的数字做异或等于0;

    1. a ^ b = b ^ a

    2. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;


public  int singleNumber(int[] nums) {

		int result = nums[0];

		for (int i = 1; i < nums.length; i++) {
			result = result ^ nums[i];
		}
		
		return result;
	}


你可能感兴趣的:(leetcode)