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

Single Number

时间:2016-07-05 10:03:58      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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/

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:
	/**
	 * @param A: Array of integers.
	 * return: The single number.
	 */
    int singleNumber(vector<int> &A) {
        // write your code here
        int single = 0;
        for(int &a : A){
            single ^= a;
        }
        return single;
    }
};

  

Single Number

标签:

原文地址:http://www.cnblogs.com/codingEskimo/p/5642314.html

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