【HackerRank】Lonely Integer 数学方法巧妙解决

Mathematical approach:

If u take every unique number in the array and sum it, then double the sum, u will have also doubled the lonely number. So when you then subtract the sum of the array from it you will be left with the only number that has not been twice in the array. python:

def lonelyinteger(a):
   sum_of_set = sum(set(a))
   sum_of_list = sum(a)
   return sum_of_set*2-sum_of_list

将集合元素乘以2,减去原数组,结果即为Unique Number。

全代码:

#!/bin/python3

import math
import os
import random
import re
import sys

#
# 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
    sum_of_set = sum(set(a));
    sum_of_list = sum(a);
    return sum_of_set*2-sum_of_list

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()

 

posted @ 2022-04-09 18:37  ka2uha  阅读(59)  评论(0)    收藏  举报