LeetCode刷题--只出现一次的数

题目

只出现一次的数字

题解

本题的关键是:找出不相同的那个数字,而且要求满足时间复杂度为线性级。
思想:异或(相同为0,不同为1),先通的两个数异或为0,0异或任何数得到原数

class Solution {
    public int singleNumber(int[] nums) {
        int ans = 0;
        for(int num:nums){
            ans = ans^num;
        }
        return ans;
    }
}

测试用例

nums= {1,1,2,2,4};
过程:

posted @ 2020-08-02 19:31  sinlearn  阅读(79)  评论(0编辑  收藏  举报