Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
29 30
Archives
Today
Total
관리 메뉴

로빈의 개발로그

HackerRank - Sparse Arrays 본문

자료구조 & 알고리즘

HackerRank - Sparse Arrays

로빈. 2022. 4. 21. 21:55

이번주에 해커랭크 1달짜리 다풀어야지.. 화이팅

 

1. 문제설명

- There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results.

 

- Example

strings = ['ab', 'ab', 'abc']

queries = ['ab', 'abc', 'bc']

 

There are  2 instances of 'ab',  1 of 'abc' and  of 'bc'.

For each query, add an element to the return array, results = [2, 1, 0]

 

- Function Description

Complete the function matchingStrings in the editor below. The function must return an array of integers representing the frequency of occurrence of each query string in strings.

matchingStrings has the following parameters:

  • string strings[n] - an array of strings to search
  • string queries[q] - an array of query strings

- Returns

  • int[q]: an array of results for each query

- Input Format

The first line contains and integer n , the size of strings[].
Each of the next n lines contains a string strings[i].
The next line contains q, the size of queries[].
Each of the next q lines contains a string queries[i].

 

2. 문제풀이

- 일단 아이디어는 쉽다. query에 있는 값이 string에 있을 경우, 카운트 값을 세서 1씩 올려주면 된다.

** HackerRank는 꼭 아웃풋쪽을 체크해야한다. join으로 값을 받기 때문에 배열로 리턴해줘야 된다..

처음에는 걍 print로 찍었다가 에러나서 다시 확인해보니 배열로 리턴해야되는 부분을 까먹었다..

엥 다시 보니 Returns 부분에 배열로 나와있다.. 문제를 잘보자!

def matchingStrings(strings, queries):
    res = []
    for i in range(len(queries)):
        count = 0
        for j in range(len(strings)):
            if queries[i] == strings[j]:
                count += 1
        res.append(count)
    return res

 

- 이중 포문 대신 count쓰기

def matchingStrings(strings, queries):
    results = []
    for item in queries:
        results.append(strings.count(item))
    return results

 

- Short code (보고 허탈해짐..)

def matchingStrings(strings, queries):
    return [strings.count(i) for i in queries]
Comments