【LeetCode 136】 关关的刷题日记32 Single Number

时间:2022-05-07
本文章向大家介绍【LeetCode 136】 关关的刷题日记32 Single Number,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记32 – Leetcode 136. 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?

题目的意思是有一个数组,每个元素出现两次,只有一个元素出现了一次,让找出该元素。

思路

思路:没细看题目,随手写了个map。

class Solution {public:
    int singleNumber(vector<int>& nums) {
        map<int,int>m;
        for(int x:nums)
        {
            m[x]++;
        }
        for(int x:nums)
        {
            if(m[x]==1)
                return x;
        }
        return 0;
    }};

方法2:发现题目要求O(n)时间复杂度,而且不需要额外空间。Map开辟了额外空间,不满足要求。采用异或的思路,遍历一边该数组即可。 aa=0 ab=ba a0=a

class Solution {public:
    int singleNumber(vector<int>& nums) {
        int re=0;
        for(int x:nums)
        {
            re^=x;
        }
        return re;
    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang,注明Leetcode刷题)。