首页 > 其他 > 详细

Single Number

时间:2016-07-05 10:01:13      阅读:179      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!