zoukankan      html  css  js  c++  java
  • leetcode-Single Number

    利用map的无重复元素特性,在第二次插入map时将对应关键字的map项删除,最后map中只有出现一次的元素:

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            map<int,int> chek;
            for(int i=0;i!=n;++i)
             if(!(chek.insert(pair<int,int>(A[i],1)).second))
                chek.erase(A[i]);
            return chek.begin()->first;
        }
    };

    自己写的有时间好了,却占用了内存空间。果断去看看大神的:

    public class Solution {
        public int singleNumber(int[] A) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            if(A == null || A.length == 0){
                return 0;
            }
            int result = A[0];
            
            for(int i = 1; i < A.length; i++){
                result = result ^ A[i];
            }
            return result;
        }
    }

    http://www.cnblogs.com/feiling/p/3349654.html

    思考:

    runtim:52ms

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            if(n==0) return 0;
            int a=A[0];
            for(int i=1;i!=n;++i)
               a^=A[i];
            return a;
        }
    };

    runtime:44ms

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            if(n==0) return 0;
            int a=0;
            for(int i=0;i!=n;++i)
               a^=A[i];
            return a;
        }
    };
    为什么时间会有这么大的差异?

  • 相关阅读:
    浅谈线段树
    浅谈KMP
    20200729线上模拟题解
    20200727线上模拟题解
    声明
    tarjan--割点,缩点
    20201029模拟
    高精模板
    二分图--二分图的几种模型
    树的直径与树的重心
  • 原文地址:https://www.cnblogs.com/huoyao/p/4248926.html
Copyright © 2011-2022 走看看