ITPub博客

首页 > > > [LeetCode] Single Number

[LeetCode] Single Number

作者:Ruiyuan Li 时间:2015-06-18 00:00:00 0 删除 编辑

Single Number

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?

解题思路:

解法一:先排序,再遍历。时间复杂度为O(nlogn),空间复杂度为O(1)。代码略。

解法二:用一个set来记录结果,若已经存在,则从set中删除。最终只留下目标数字。时间复杂度为O(n),空间复杂度为O(n)。

解法三:位操作。注意,两个相同数字异或为0,0与任何数字异或等于该数字本身。这样时间复杂度为O(n),空间复杂度为O(1)。

class Solution {
public:
    int singleNumber(vector& nums) {
        int result = 0;
        int len = nums.size();
        for(int i=0; i


转载请注明: » [LeetCode] Single Number
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4826