1、题目数组
一、审题spa
二、分析code
在线性时间复杂度、常量空间开销的状况下统计出一个整形数组中只出现一次的两个数(其余的数都是出现2次)。blog
2、解答it
一、思路ast
①、对数组全部元素进行异或(^) 操做,获得只出现 1 次的这两个数的异或结果 diff。class
②、diff &= -diff ,获得只出现一次的两个数的二进制形式的第一个不一样的位置 a。遍历
③、初始化结果数组{0, 0},遍历数组中的元素,若 a = 1,则与结果数组中第一个元素进行异或;若 a = 0 ,则与第二个元素进行异或。二进制
④、返回结果数组。im
public int[] singleNumber(int[] nums) { // Pass 1 : // Get the XOR of the two numbers we need to find int diff = 0; for(int num: nums) diff ^= num; // Get its last set bit diff &= -diff; // Pass 2 : int[] rets = {0, 0}; for(int num: nums) { if((num & diff) == 0) rets[0] ^= num; else rets[1] ^= num; } return rets; }