LeetCode_136_SingleNumber

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode_136_SingleNumber相关的知识,希望对你有一定的参考价值。

136. Single Number

 

Total Accepted: 122616 Total Submissions: 248345 Difficulty: Medium

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?

 

题目分析:

给定一个数组,其中每个元素都重复了两次,只有一个元素出现了一次,找出这个元素.

要求T(n) = O(n),并且不开辟新的内存空间(C++无法做到,姑且认为 S(n) = O(1)).

 

解:

XOR相关知识:

A^A = 0

A^0 = A

A^A^B = B

且XOR满足交换律和分配律

 

Solution

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

 

 

T(n) = O(n)

S(n) = O(1)

以上是关于LeetCode_136_SingleNumber的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-136 Single Number

Leetccode 136 137 260 SingleNumber I II III

LeetCode 136. Single Number & 268. Missing Number

27.leetcode136_single_number

三种方法任君挑选 LeetCode_136只出现一次的数字

Leetcode 5