Lonely Integer

HackerRank 問題: Lonely Integer

Question

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

HackerRank 問題: Lonely Integer

Answer

<?php

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

function lonelyinteger($number_list) {
    // Write your code here

    $number_occur_mapping = [];
    $lonely_number_candidate = [];
    $lonely_number = null;

    // search lonely number
    foreach ($number_list as $number) {
        if (!isset($number_occur_mapping[$number])) {
            // this number is lonely
            $lonely_number_candidate[$number] = $number;
        } else {
            // remove previous lonely number
            unset($lonely_number_candidate[$number]);
        }
        $number_occur_mapping[$number] = 1;
    }
    // get first lonely number
    $lonely_number = array_pop($lonely_number_candidate);

    return $lonely_number;

}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$n = intval(trim(fgets(STDIN)));

$a_temp = rtrim(fgets(STDIN));

$a = array_map('intval', preg_split('/ /', $a_temp, -1, PREG_SPLIT_NO_EMPTY));

$result = lonelyinteger($a);

fwrite($fptr, $result . "\n");

fclose($fptr);

Reference