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

Find one unique integer

时间:2017-06-06 23:29:07      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:network   change   count   type   algo   clu   ref   can   app   

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

标签:network   change   count   type   algo   clu   ref   can   app   

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

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