136. 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

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

用异或

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

要有默认返回值:返回0

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

^= 好用

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

//for loop ^=
        for (int i = 0; i < nums.length; i++) {
            n ^= nums[i];
        }

[其他解法]:

[Follow Up]:

137. Single Number II 出现三次:与

260. Single Number III 2个一次 

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public int singleNumber(int[] nums) {
        //ini n
        int n = 0;
        
        //for loop ^=
        for (int i = 0; i < nums.length; i++) {
            n ^= nums[i];
        }
        
        //return
        if (n != 0) return n;
        
        return 0;
    }
}
View Code

 

posted @ 2018-04-24 16:35  苗妙苗  阅读(424)  评论(0编辑  收藏  举报