Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Explanation:
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
Example 2:
Input: arr = [400]
Output: [-1]
Explanation: There are no elements to the right of index 0.
Constraints:
- 1 <= arr.length <= 104
- 1 <= arr[i] <= 105
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
#해당 인덱스 제외 오른쪽의 가장 큰것 나오기
#없으면 -1 대체
#시간 초과
result_list = []
if len(arr) == 1:
result_list.append(-1)
return result_list
print(len(arr))
l_max_index = arr.index(max(arr[1:]))
for i in range(len(arr)):
if i != len(arr) - 1:
if i == l_max_index:
l_max_index = arr.index(max(arr[i+1:]))
elif i > l_max_index:
l_max_index = l_max_index = arr.index(max(arr[i+1:]), i)
l_max = arr[l_max_index]
else:
l_max = -1
result_list.append(l_max)
return result_list
결과로 알수 있듯이 좋은 코드는 아닙니다.
아래 내용을 참조하세요
https://www.youtube.com/watch?v=ZHjKhUjcsaU
'알고리즘 > 배열(array)' 카테고리의 다른 글
Sort Array By Parity python (0) | 2023.07.05 |
---|---|
Move Zeroes python (0) | 2023.07.05 |
Valid Mountain Array python (0) | 2023.07.02 |
Check If N and Its Double Exist python (0) | 2023.07.01 |
Remove Duplicates from Sorted Array python (0) | 2023.06.29 |