首页 > 其他 > 详细

[LeetCode]136 Single Number

时间:2015-01-08 18:15:05      阅读:303      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!