CodingSpace

[HackerRank/Algorithms] Implementation - Equalize the Array 본문

HackerRank/Algorithm

[HackerRank/Algorithms] Implementation - Equalize the Array

개발자_조이킴 2022. 9. 8. 23:50

Problem. Implementation - Equalize the Array


Link.

https://www.hackerrank.com/challenges/equality-in-a-array/problem?isFullScreen=true 

 

Equalize the Array | HackerRank

Delete a minimal number of elements from an array so that all elements of the modified array are equal to one another.

www.hackerrank.com


Description.

Given an array of integers, determine the minimum number of elements to delete to leave only elements of equal value.


Key Point. 


My Answer. 

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

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

function equalizeArray(arr) {
    // 배열 arr의 전체 길이
    let totalLen = arr.length;
    let obj = {};
    // 각 요소별 중복되는 개수를 키-값으로 저장
    arr.forEach((el) => {
        obj[el] = (obj[el] || 0) + 1;
    })
    // 각 키의 값들을 배열로 저장
    let array = Object.values(obj);
    // 중복된 값 중 가장 큰 값을 변수 max에 저장
    let max = Math.max(...array);
    // 전체 길이에서 max를 뺀 값을 반환
    return totalLen - max;
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const n = parseInt(readLine().trim(), 10);

    const arr = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));

    const result = equalizeArray(arr);

    ws.write(result + '\n');

    ws.end();
}

References. 

 

Comments