티스토리 뷰

반응형
2021.03.14      
답봄      

풀다풀다 안돼서 다른 사람 풀이를 보고 풀었다. 다시 봐야하는 문제다. 덕분에 많은 것을 고민할 수 있던 문제였다.

  • 우선 배열을 초기화 할 때, A=[0]*N 이나 A=[0 for i in range(N)]이나 똑같은 O(N) 이다. 나 혼자 쉽다고 * 남발하다가는 파이썬의 깊은 복사 얕은 복사에 걸려 2중 배열 할때 A=[[0]]*N 이런식으로 코드 짜고선 어 웨완뒈 이러면서 울기 싫으면 반복문을 명시적으로 작성하는 것이 좋다.
  • 이게.. O(N+M) 이라니.. 혼자선 안냈을 답이다. 좀 더 연습하자.

Task description

You are given N counters, initially set to 0, and you have two possible operations on them:

  • _increase(X)_− counter X is increased by 1,
  • _max counter_− all counters are set to the maximum value of any counter.

A non-empty array A of M integers is given. This array represents consecutive operations:

  • if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
  • if A[K] = N + 1 then operation K is max counter.

For example, given integer N = 5 and array A such that:

A[0] = 3 A[1] = 4 A[2] = 4 A[3] = 6 A[4] = 1 A[5] = 4 A[6] = 4

the values of the counters after each consecutive operation will be:

(0, 0, 1, 0, 0) (0, 0, 1, 1, 0) (0, 0, 1, 2, 0) (2, 2, 2, 2, 2) (3, 2, 2, 2, 2) (3, 2, 2, 3, 2) (3, 2, 2, 4, 2)

The goal is to calculate the value of every counter after all operations.

Write a function:

def solution(N, A)

that, given an integer N and a non-empty array A consisting of M integers, returns a sequence of integers representing the values of the counters.

Result array should be returned as an array of integers.

For example, given:

A[0] = 3 A[1] = 4 A[2] = 4 A[3] = 6 A[4] = 1 A[5] = 4 A[6] = 4

the function should return [3, 2, 2, 4, 2], as explained above.

Write anefficientalgorithm for the following assumptions:

  • N and M are integers within the range [1..100,000];
  • each element of array A is an integer within the range [1..N + 1].
반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 31
글 보관함