码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode single-number

时间:2017-08-26 22:11:56      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:不能   app   array   ber   number   integer   0ms   exit   linear   

题目描述

 

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?

 

我的解题思路:不能使用额外空间,时间要线性,粗暴的方法就是两个循环

 
在下的代码 时间213ms 空间13164k
public class Solution {
    public int singleNumber(int[] A) {
        for (int i=0;i<A.length;i++){
            Boolean twice = false;
            for (int j= 0;j<A.length;j++){
                if (i == j)
                    continue;
                if (A[i] == A[j]){
                    twice = true;
                    break;
                }
            }
            if (!twice){
                return A[i];
            }
        }
        return 0;
    }
}

  

大神代码 时间150ms 空间12952k 异或的思路就是好啊,两个相同的数异或为0

public class Solution {
    public int singleNumber(int[] A) {
        int num = 0;
        for(int i=0;i<A.length;i++){
            num^=A[i];
        }
        return num;
    }
}

  

 

leetcode single-number

标签:不能   app   array   ber   number   integer   0ms   exit   linear   

原文地址:http://www.cnblogs.com/Melinni/p/7436466.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!