标签: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
原文地址:http://7371901.blog.51cto.com/7361901/1600764