首页 > 其他 > 详细

Find one unique integer

时间:2017-06-06 22:54:15      阅读:306      评论:0      收藏:0      [点我收藏+]

https://github.com/Premiumlab/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Mock%20Interviews/Social%20Network%20Company/Social%20Network%20Company%20-%20Interview%20Questions%20-%20SOLUTIONS/On-Site%20Question%202%20-%20SOLUTION.ipynb

 

 

On-Site Question 2 - SOLUTION

Problem

Given a list of account ID numbers (integers) which contains duplicates , find the one unique integer. (the list is guaranteed to only have one unique (non-duplicated) integer

Requirements?

Do not use built-in Python functions or methods

 

Solution

This should feel very familiar to one of the problems we did in the array section of the course! We can use an XOR operation. The exclusive or operations will take two sets of bits and for each pair it will return a 1 value if one but not both of the bits is 1.

In Python we can use the ^ symbol to perform an XOR.

Now for our solution we can simply XOR all the integers in the list. We start with a unique id set to 0, then every time we XOR a new id from the list, it will change the bits. When we XOR with the same ID again, it will cancel out the earlier change.

By the end, we wil be left with the ID that was unique and only appeared once!

 

def solution(id_list):
    
    # Initiate unique Id
    unique_id = 0
    
    # XOR fo revery id in id list
    for i in id_list:
        
        # XOR operation
        unique_id ^= i
    
    return unique_id

 

 

Good Job!

Find one unique integer

原文:http://www.cnblogs.com/prmlab/p/6953739.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!