这一系列的题目是源自于LeetCode--136. Single Number以及LeetCode--137. Single Number II和LeetCode--260. Single Number III我们先做题,然后在进行扩展。
Single Number:
原题目:
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
题目意思很明确了,只有一个数字出现了一次,其余数字出现了两次。
分析:这题有很多解法:1、暴力法O(N^2)。2、使用hash表,时间复杂度O(N),空间复杂度O(N)。3,使用位运算,时间复杂度O(N),空间复杂度O(1)。
这里我们只给出第三种解法,也是最优解法。我们知道一个数与自身异或的结果为0,与0异或的结果就是它自身,所以我们将数组中所有的元素之间做异常操作就得到了那个只出现一次的数了:
AC代码:
public int singleNumber(int[] nums) {
int res