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

[LeetCode]136 Single Number

时间:2015-01-08 18:16:14      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/single-number/

http://blog.csdn.net/linhuanmars/article/details/22648829

public class Solution {
    public int singleNumber(int[] A) 
    {
        // Solution A
        // return singleNum_Xor(A);
        
        // Solution B
        return singleNum_BitCompare(A);
        
        // Solution C
        // return singleNum_Map(A);
    }
    
    
    ///////////////////////
    // Solution A: Xor
    //
    private int singleNum_Xor(int[] A)
    {
        int toReturn = 0;
        for (int i : A)
        {
            toReturn = toReturn ^ i;
        }
        return toReturn;
    }

    ///////////////////////
    // Solution A: BitCompare
    //    
    private int singleNum_BitCompare(int[] A)
    {
        int toReturn = 0;
        for (int d = 0 ; d < 32 ; d ++)
        {
            int toCompare = 1 << d;
            int occr = 0;
            for (int i : A)
            {
                if ((i & toCompare) != 0)
                {
                    occr++;
                }
            }
            if (occr % 2 == 1)
            {
                toReturn |= toCompare;
            }
        }
        return toReturn;
    }

    ///////////////////////
    // Solution A: Map
    //     
    private int singleNum_Map(int[] A)
    {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : A)
        {
            Integer occr = map.get(i);
            if (occr == null)
                occr = 0;
            occr ++;
            map.put(i, occr);
        }
        
        for (Map.Entry<Integer, Integer> entry : map.entrySet())
        {
            if (entry.getValue() == 1)
                return entry.getKey();
        }
        return -1;
    }
}


[LeetCode]136 Single Number

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1600764

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