zoukankan      html  css  js  c++  java
  • LeetCode 136. Single Number

    136. Single Number

    • Total Accepted: 173470
    • Total Submissions: 331880
    • Difficulty: Easy
    • Contributors: Admin

    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?

    Subscribe to see which companies asked this question

    题意:给你一个动态数组,里面的数只有一个数出现过一次其余的数都出现过两次,让你在不另辟空间的情况下用O(n)的复杂度实现,真是神奇的算法,能想到的也只有快排那些O(n*lgn)的东西
    实现:因为A和A的异或等于0,而A和0的异或等于A,所以将整个数组遍历每个数异或一遍的结果就是要找的那个数,是不是很神奇
     
    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int i = 1;
            while(i<nums.size())
            {
                nums[i]=nums[i-1]^nums[i];
                i++;
            }
            return nums[i-1];
        }
    };
     
  • 相关阅读:
    __file__ 作用以及模块导入方法
    random 模块
    time 模块
    module模块和包
    装饰器
    python闭包
    filter map reduce函数的使用
    python文件处理
    python内置函数使用
    函数
  • 原文地址:https://www.cnblogs.com/Xycdada/p/6076105.html
Copyright © 2011-2022 走看看