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

lintcode-medium-Single Number III

时间:2016-04-06 07:06:09      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

Given 2*n + 2 numbers, every numbers occurs twice except two, find them.

 

Example

Given [1,2,2,3,4,4,5,3] return 1 and 5

Challenge

O(n) time, O(1) extra space.

 

public class Solution {
    /**
     * @param A : An integer array
     * @return : Two integers
     */
    public List<Integer> singleNumberIII(int[] A) {
        // write your code here
        
        if(A == null || A.length == 0)
            return new ArrayList<Integer>();
        
        List<Integer> res = new ArrayList<Integer>();
        
        int temp = A[0];
        for(int i = 1; i < A.length; i++)
            temp ^= A[i];
        
        int index = 0;
        for(int i = 0; i < 32; i++){
            if(((temp >> i) & 1) == 1){
                index = i;
                break;
            }
        }
        
        Integer res1 = null;
        Integer res2 = null;
        
        for(int i = 0; i < A.length; i++){
            
            if(((A[i] >> index) & 1) == 1){
                if(res1 == null){
                    res1 = A[i];
                }
                else{
                    res1 ^= A[i];
                }
            }
            else{
                if(res2 == null){
                    res2 = A[i];
                }
                else{
                    res2 ^= A[i];
                }
            }
            
        }
        
        res.add(res1);
        res.add(res2);
        
        return res;
    }
}

 

lintcode-medium-Single Number III

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5357671.html

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