• 136. Single Number


    Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

    Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?

    Example 1:

    Input: nums = [2,2,1]
    Output: 1
    

    Example 2:

    Input: nums = [4,1,2,1,2]
    Output: 4

    Constraints:

    • 1 <= nums.length <= 3 * 104
    • -3 * 104 <= nums[i] <= 3 * 104
    • Each element in the array appears twice except for one element which appears only once.

    解法一:遍历数组中的每个数,如果这个数存在集合s中,就从集合中删掉此数,否则,把这个数插入集合中。遍历结束后,集合中剩下的唯一的数就是single number。

    时间复杂度O(n),空间复杂度O(n)

    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            unordered_set<int> s;
            int n=nums.size();
            for(int i=0;i<n;i++){
                if(s.count(nums[i]))
                    s.erase(nums[i]);
                else s.insert(nums[i]);
            }
            return *s.begin();
        }
    };
    Runtime: 32 ms, faster than 20.54% of C++ online submissions for Single Number.
    Memory Usage: 19.9 MB, less than 19.77% of C++ online submissions for Single Number.
    解法二、用异或运算。一个数与其本身进行异或,等于0,一个数和0进行异或,等于这个数本身。异或运算满足交换律和结合律,即A^B^A=B。
    时间复杂度O(n),空间复杂度O(1)
    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int ans=0;
            for(int i=0;i<nums.size();i++)
                ans^=nums[i];
            return ans;
        }
    };
    Runtime: 12 ms, faster than 97.15% of C++ online submissions for Single Number.
    Memory Usage: 16.8 MB, less than 97.90% of C++ online submissions for Single Number.
  • 相关阅读:
    软件测试—— junit 单元测试
    falut error failure 的区别与理解
    错误的反思
    只能在微信浏览器打开的链接,如何查看源码
    PHPManage for IIS Windows 10
    wamp mysql配置
    CSS Flexbox 学习指南、工具与框架
    Android SDK 在线更新镜像服务器资源
    64位win2003 IIS6运行32位的.NET程序
    让服务器iis支持.apk文件下载的设置方法
  • 原文地址:https://www.cnblogs.com/Makerr/p/14680965.html
Copyright © 2020-2023  润新知