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