zoukankan      html  css  js  c++  java
  • 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.
  • 相关阅读:
    iOS之地理位置及定位系统 -- 入门笔记(用Swift)
    网易新闻iOS版使用的18个开源组件
    自学 iOS – 三十天三十个 Swift 项目
    iOS之UI--富文本总结
    IOS开发--横向流水布局实现
    IOS开发--仿制网易新闻
    Runtime 方法替换 和 动态添加实例方法 结合使用
    写给IOS开发工程师的网页前端入门笔记
    Runtime(动态添加属性)
    const,static,extern简介(重要)
  • 原文地址:https://www.cnblogs.com/Makerr/p/14680965.html
Copyright © 2011-2022 走看看