티스토리 뷰

1Day 1Algorithm

[DAY 1] Sock Merchant

walk_through_me 2019. 10. 1. 20:05

John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are n=7 socks with colors ar=[1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.

 

 

Sock Merchant | HackerRank

How many pairs of socks John can sell?

www.hackerrank.com

 

소요시간 : 6분

 

 

풀이

function sockMerchant(n, ar) { 
    let pair = 0;

    ar.sort();
   

    for(let i = 0; i < n; i++) {
        
        if(ar[i] == ar[i+1]) {
            pair++;
            i++;
        }
    }

    return pair;

}

1. sort()를 이용해 ar을 정렬함

2. for문을 돌면서 현재 값이 다음 값과 같으면 pair에 1개를 추가해줌

3. 이때, 중복된 값이 들어가지 않도록 i에 1을 더해줌

4. pair를 반환함

 

 

다른 사람의 풀이

var ones = {}, pairs = 0;
for (var i = 0; i < n; i++) {
    if (ones.hasOwnProperty(ar[i])) {
        pairs++;
        delete ones[ar[i]];
    } else {
        ones[ar[i]] = 0;
    }
}
return pairs;

1. sort()를 사용하지 않고 Object를 생성함(작성자 피셜, sort() 쓰는 것보다 빠르다고함)

2. hasOwnProperty를 이용해 프라퍼티가 있으면 pair 값을 1 더해주고, Ones Object에서 해당 값을 삭제함.

3. 값이 없으면 0개로 추가를 해줌. 

'1Day 1Algorithm' 카테고리의 다른 글

[DAY 6] Recursion: Fibonacci Numbers  (0) 2019.10.06
[DAY 5] Flipping bits  (0) 2019.10.05
[DAY 4] Bitwise Operators  (0) 2019.10.04
[DAY 3] Compare the Triplets  (0) 2019.10.03
[DAY 2] Simple Array Sum  (0) 2019.10.02
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함