Interview Preparation Kits > 1 Week Preparation Kit > Day 2 > Lonely Integer

 

Given an array of integers, where all elements but one occur twice, find the unique element.

 

Example

a = [1, 2, 3, 4, 3, 2, 1]

The unique element is 4.

 

Function Description

Complete the lonelyinteger function in the editor below.

lonelyinteger has the following parameter(s):

  • int a[n]: an array of integers

 

Returns

  • int: the element that occurs only once

 

Input Format

The first line contains a single integer, n, the number of integers in the array.

The second line contains n space-separated integers that describe the values in a.

 

Constraints

  • 1 <= n < 100
  • It is guaranteed that n is an odd number and that there is one unique element.
  • 0 <= a[i] <= 100, where 0 <= i < n.

#!/bin/python3

import math
import os
import random
import re
import sys
import collections


#
# Complete the 'lonelyinteger' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY a as parameter.
#

# def lonelyinteger(a):
#     # Write your code here
#     arr = []
#     temp = collections.Counter(a)
#     for i in sorted(temp.items()):
#         arr.append(i)
#     print(arr[-1][0])
#     return arr[-1][0]

def lonelyinteger(a):
    # Write your code here
    arr = []
    temp = collections.Counter(a)
    for i in (temp.items()):
        num, cnt = i
        if cnt == 1:
            return num
    
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    a = list(map(int, input().rstrip().split()))

    result = lonelyinteger(a)

    fptr.write(str(result) + '\n')

    fptr.close()

- sort와 sorted의 명확한 차이에 대해 다시 한 번 공부해야겠다. 

- collections의 counter 메소드는 매우 유용하므로 알고 있으면 좋을 것이다!

+ Recent posts