[LeetCode] 136. Single Number
There are two ways for the problem:
1. Tradition: Setup a map or set.
2. Bit operation: x ^ x = 0; so if the number keep XOR, the same ones will cancel each other, the one that left would be the single number.
http://www.programcreek.com/2012/12/leetcode-solution-of-single-number-in-java/
这道题需要注意异或的几个知识点:
- a^0 = a
- a^a = 0
- a^b = b^a
- a^b^c = a^(b^c)
- 得到一个数二进制最右位为1,其余为0的模:a &(~a+1) (~a + 1) = -a =>这道题用不上,但这个知识点很有用。
public class Solution { /** *@param A : an integer array *return : a integer */ public int singleNumber(int[] A) { // Write your code here Map<Integer, Integer> base = new HashMap<Integer, Integer>(); for(int a : A){ if(base.containsKey(a)){ base.put(a, 1); } else { base.put(a, 0); } } int result = 0; for (Map.Entry<Integer, Integer> entry : base.entrySet()){ if (entry.getValue() == 0){ result = entry.getKey(); break; } } return result; } }
class Solution { public int singleNumber(int[] nums) { if (nums == null || nums.length == 0) { return Integer.MIN_VALUE; } int eor = 0; for (int i = 0; i < nums.length; i++) { eor ^= nums[i]; } return eor; } }
posted on 2016-07-05 08:49 codingEskimo 阅读(123) 评论(0) 编辑 收藏 举报