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;
        }
    };
    为什么时间会有这么大的差异?

  • 相关阅读:
    第六周学习报告
    第五周学习任务报告
    第四周学习任务报告
    第三周学习任务报告
    第二周(9.14-9.20)学习任务报告
    Top 参数解析
    unpipc.h
    linux 网络编程卷2 笔记
    mysql 主从及配置
    rsync linux
  • 原文地址:https://www.cnblogs.com/huoyao/p/4248926.html
Copyright © 2011-2022 走看看