https://leetcode.com/problems/defuse-the-bomb/
Defuse the Bomb - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제: 문제에서 주어진 조건에 따라, 배열 원소의 합을 반환하는 문제
문제 설명:
정수가 담긴 배열과 k라는 값이 주어집니다.
다음과 같이 총 3가지 조건에 따라 문제를 풀이하는 방법이 달라집니다.
- k > 0 일 경우, 배열의 i번째 값은 i번째 이후 k개의 원소의 합으로 대체됩니다.
예를 들어, [5, 7, 1, 4] 이라는 배열과 k = 3 이라는 값이 주어질 경우, 0번째는 7+1+4 (==12) 로 대체되고 1번째 값은 1+4+5(==10)으로 대체됩니다.
따라서 최종 반환되는 배열은 [12, 10, 16, 13] 이 됩니다.
- k < 0 일 경우, 배열의 i번째 값은 i번째 이전 k개의 원소의 합으로 대체됩니다.
예를 들어, [2, 4, 9, 3] 이라는 배열과 k = -2 라는 값이 주어질 경우, 0번째는 3+9 (==12)로 대체 되고 1번째 값은 2+3 (==5)로 대체됩니다.
따라서 최종 반환되는 배열은 [12, 5, 6, 13] 이 됩니다.
- 마지막으로 k = 0 일 경우, 배열의 모든 원소는 0이 되어 반환됩니다.
풀이 코드:
class Solution:
def decrypt(self, code: List[int], k: int) -> List[int]:
length = len(code)
lst = []
if k > 0:
for i in range(length):
s = 0
for j in range(1, k + 1):
s += code[(i + j) % length]
lst.append(s)
elif k < 0:
for i in range(length):
s = 0
for j in range(1, abs(k) + 1):
s += code[i + (-1 * j)]
lst.append(s)
else:
return [0] * length
return lst
'알고리즘 > Leetcode' 카테고리의 다른 글
[Leetcode /python] 530. Minimum Absolute Difference in BST (0) | 2022.11.21 |
---|---|
[Leetcode / python] 777번,2337번 공통 풀이 (0) | 2022.11.17 |
[Leetcode / python] 2079. Watering Plants (0) | 2022.11.16 |
[Leetcode / python] 2. Add Two Numbers (0) | 2022.11.15 |
[Leetcode / python] 1207. Unique Number of Occurrences (0) | 2022.11.14 |