강의

멘토링

로드맵

Inflearn Community Q&A

jsschannel991410's profile image
jsschannel991410

asked

Introduction to Javascript Algorithm Problem Solving (Coding Test Preparation)

6. Class President (Hash Map)

후보가 다섯명이어서 직접 오브젝트를 생성했습니다.

Written on

·

316

0

function solution (str){
            let cnt = {
                'A':0,
                'B':0,
                'C':0,
                'D':0,
                'E':0,
            }
            for(let i=0; i<str.length ;i++){
                if(str[i] === 'A') cnt['A']++;
                else if(str[i] === 'B') cnt['B']++;
                else if(str[i] === 'C') cnt['C']++;
                else if(str[i] === 'D') cnt['D']++;
                else cnt['E']++;
            }
            const sortable = Object.fromEntries(Object.entries(cnt).sort(([,a],[,b]) => b-a));
            return Object.keys(sortable)[0];
        }

안녕하세요. map 개념을 잘 몰라서 오브젝트 직접 생성해서 정렬하고 답을 구했습니다. 

1. 이 경우 시간복잡도는 O(n)이 맞을까요?

2. 다른 해쉬 문제에서도 이렇게 해도 괜찮을까요? (여기서는 후보가 다섯명뿐이라 쉽게 구현했지만.. 수가  많아지면 힘들어질까요..??)

좋은 강의 감사합니다.

javascript코테 준비 같이 해요!

Quiz

45% of people got it wrong. Give it a try!

What is the main reason why two-pointer or sliding window techniques are more efficient than nested loops?

Because it uses less memory?

Is it because the code is shorter?

Is it because it achieves O(N) time complexity in most cases?

Is it because it's not affected by the input data size?

Answer 2

1

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

네 위에 코드도 O(n)입니다.

해쉬문제는 Map객체를 사용하시는게 좋습니다. 

0

같은 key가 이미 존재할 때는 덮어씌워지기 때문에 for문 안에 if문으로 체크하지 않고 cnt[str[i]] += 1; 라고 쓸 수 있습니다!! 

jsschannel991410's profile image
jsschannel991410

asked

Ask a question