【Leetcode】Single Number

题目链接:https://leetcode.com/problems/single-number/

题目:

Given an 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?

思路:

1、用HashMap,时间复杂度O(n),空间复杂度O(n)

2、用位操作,考虑异或的特点:x^x=0,异或满足结合律和交换律,0^x=x。

对数组所有元素异或一次,即n[0]^n[1]^n[2].....运用交换律和结合律可以把相同元素放一起异或结果为0,而0和剩余元素异或不会改变结果,所以

最后得到结果 为出现次数为奇数的元素。空间复杂度为O(1)。

算法1:

public int singleNumber(int[] nums) {
		Map<Integer, Integer> maps = new HashMap<Integer, Integer>();
		for (int i : nums) {
			if (maps.containsKey(i)) {
				maps.remove(i);
			} else {
				maps.put(i, 1);
			}
		}
		return (int) maps.keySet().toArray()[0];
	}


算法2:

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


你可能感兴趣的:(【Leetcode】Single Number)