LeetCode136——只出现一次的数字

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/85676486

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/single-number/description/

题目描述:

知识点:位运算

思路:利用按位异或运算符的性质:N ^ N = 0,0 ^ N = N

题目明确表示除了某个元素只出现一次外,其余每个元素均出现2次,因此其余的两个相同的元素按位异或均得0,而0和那个只出现一次的元素异或就得到了那个只出现一次的元素。

时间复杂度是O(n),其中n为数组的大小。空间复杂度是O(1)。

JAVA代码:

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

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/85676486