티스토리 뷰

Algorithms

Equalize the Array

seoca 2020. 12. 11. 00:10

주어진 array 에서 최대로 중복되는 index를 제외한 나머지 index의 수를 구하는 문제 

 

solution  

1. 중복을 허용하지 않는 hashMap 을 선언.

2. 주어진 arr를 hashMap안에 넣으면서 중복되는 값이 있으면 value의 값이 1씩 증가하게 한다. 

3. maximum value의 수를 찾는다.

4. 전체 array길이에서 찾아낸 maximum value를 return한다.  

 

 

 

 

Solution 1

-object를 이용하는 traditional way 말고 built-in function 인 Map을 이용하는 방식.

function equalizeArray(arr) {
    //let arrObj = {}; //initialize object which is for hashmap.
    //but using js object is traditional way to make hashmap
    const arrObj = new Map();

    let maxCount = 0;

    //find duplicate index and remove them using hashmap because hashMap doesnt allow duplicates
    for (let num of arr) {
        arrObj[num] = arrObj[num] + 1 || 1;
    }
    
    for (let value in arrObj) {
        if (arrObj[value] > maxCount) {
            maxCount = arrObj[value];
        }
    }
        
    return (arr.length - maxCount);
}

- Javascript {} 는 Object initialization.

- Javascript object는 hashmap 을 만드는 traditional way. 

- for (let num of arr) {
        arrObj[num] = arrObj[num] + 1 || 1;  // 처음에 num 이 arrObj[num] 에 있으면 true 아니면 falsy. 처음에는 없으니 1이 들어간다.
    }

- arrObj[num] 이런식으로 넣으면 key값으로 들어간다. 

 

 

 

 

 

Solution 2

const arr = [3, 3, 1, 4, 3, 4];

function equalizeArray(arr) {
    let object = new Map();

    //count the duplication
    for (let num of arr){
        if(!object[num]) object[num] = 0;
        object[num]++;
    }

    //Return the number with the highest value
    //Object.value() returns an array
    let mostRepeated = Math.max(...Object.values(object)); 
    
    let result = arr.length - mostRepeated;

    //return result;
    return result;
}

let result = equalizeArray(arr);
console.log(result);

 

 

 

 

 

 

 

 

 

 

 

Reference

www.hackerrank.com/challenges/equality-in-a-array/problem

 

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

646634.medium.com/how-to-solve-hackerranks-equalize-the-array-problem-e3ceebd7c866

 

How to solve HackerRank’s Equalize The Array Problem

As a recent coding bootcamp grad, I quickly realized that I needed to get more comfortable with data structures and algorithms if I wanted…

646634.medium.com

medium.com/better-programming/stop-using-objects-as-hash-maps-in-javascript-9a272e85f6a8

 

Stop Using Objects as Hash Maps in JavaScript

There’s a better way to do that

medium.com

medium.com/@oprearocks/what-do-the-three-dots-mean-in-javascript-bc5749439c9a

 

What do the three dots (…) mean in JavaScript?

Originally published at https://oprea.rocks/blog/what-do-the-three-dots-mean-in-javascript/

medium.com

 

'Algorithms' 카테고리의 다른 글

smallest distance  (0) 2021.01.16
Cut the sticks  (0) 2020.12.18
Invert Binary Tree  (0) 2020.11.30
Sequence Equation  (0) 2020.10.30
Viral Advertising  (0) 2020.10.22