Leetcode136. Single Number | XOR

1.Description
There is an integer array. In this array, only one element appears once and other elements appears twice. The task is to find the element which appears once using an algorithm whose time complexity is O(n) and space complexity is O(1).
2.Algorithms I used
XOR operations
3.Analysis
At first, I use QuickSort to solve this problem. By using QuickSort, the array becomes ordered. For an ascending array, we can find the element which appears once by iterating the array, While iterating, we compare one element and its former element. If they are not equal, the current element is the answer. I have completed it below.

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        if(nums.size() == 1) return nums[0];
        if(nums[0] != nums[1]) return nums[0];
        if(nums[nums.size()-1] != nums[nums.size()-2]) return nums[nums.size()-1];
        for(int i = 0;i < nums.size();i+=2){
            if(nums[i] != nums[i+1]) 
                return {nums[i]};
        }
        return 0;
    }
};

However, this solution’s time complexity is O(nlogn). It doesn’t meet the requirement.
I didn’t come up with a better answer.
After reading other’s solution, I know that this problem should be solved by XOR operations. For this problem, we have to know 3 rules about XOR.
First, any number XOR 0 remains 0.
Second, the XOR result of two same numbers is 0 and the XOR result of two different numbers is 1.
Third, XOR operation satisfys the commutative law and the associate law.
Hence, we can XOR all elements in the array. By using the commutative law, the final equation is 0XOR0XOR0XOR0…XORans. Every 0 in this equation is a XOR result of two same numbers. And ans is the element we want.
4.code

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ans = 0;
        for(int i = 0;i < nums.size();i++){
            ans ^= nums[i];
        }
        return ans;
    }
};

5.Complexity
TIme complexity: O(n).
Space complexity: O(1).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值