[Leetcode] Single Number

Single Number 题解

题目来源:https://leetcode.com/problems/single-number/description/


Description

Given an 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?

Solution

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

解题描述

这道题题意是,给出一个数组,数组中有一个数字只会出现一次,其他所有数字都会出现两次。另外,解法上题目要求时间复杂度和空间复杂度均为常数级别。

要使时间复杂度保持常数级别,第一个想到的可能是采用哈希。但是哈希会造成O(n)的空间复杂度,并且最终查找到只出现一次的那个数字的查找过程会造成额外的时间开销。

上面给出的是采用异或的解法,利用相同的数字异或为0的性质,将数组中所有数字进行异或之后,最终的结果就是要查找的只出现一次的数字。

原文地址:https://www.cnblogs.com/yanhewu/p/8685849.html