Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
풀이
단순하게 슬라이싱을 통해서 두 리스트를 나눈 뒤 합치면 되겠다고라고 생각했지만 리트코드에서는 nums 내부에서 해결하길 원한다.. 백준을 풀때는 단순히 문제를 풀면 된다는 생각에 메모리 상관없이 사용했던거같은데 리트코드를 풀면서 새로운 부분을 깨닫게 된다.
처음에 단순하게 각 리스트를 k번쨰 인덱스부터 k를 인덱스를 합쳐서 넣자고 생각하고 문제를 풀었더니 틀렸다
로테이션으로 값이 한칸씩 움직이길 원하는데 원소의 개수만큼 더해주고 빼주는 방식으로하게되면 nums =[0] 또는 nums=[1,2]의 케이스에서 답안이 계속 틀렸다
최초의 코드
class Solution:
def rotate(self,nums, k):
len_num= len(nums)
result = nums[-k:] + nums[:len_num-k]
nums.clear()
for i in result:
nums.append(i)
k가 범위를 넘어설때 그냥 k를 총 원소의 개수로 나누고 k번째인덱스의 앞부분과 뒷부분을 나눠서 슬라이싱한 후 다시 합쳐서 넣어주면 되었다.
이후에 전의 문제에서 배운 [:] 현재 배열에서 원소를 조작하는 방법을 통해 문제를 풀었던게 생각나서 다른 배열을 추가하지 않고 인덱스 내에서 재조합되게 만들었다.
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
len_num= len(nums)
k= k%len_num
result = nums[-k:] + nums[:-k]
nums.clear()
for i in result:
nums.append(i)
def rotate(nums, k):
if len(nums)!=1 and k !=0:
len_num= len(nums)
k = k%len_num
nums [:]= nums[-k:] + nums[:len_num-k]
print(nums)
다른사람이 작성한 슬라이싱을 사용하지 않고 리스트를 추가하여 각 인덱스의 숫자를 넣어서 다시 새배열에 배치하는 방법
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
a = [0] * len(nums)
for i in range(len(nums)):
a[(i+k)%len(nums)] = nums[i] #recycle
for i in range(len(nums)):
nums[i] = a[i]
'알고리즘 > LeetCode' 카테고리의 다른 글
LeetCode 121. Best Time to Buy and Sell Stock II (0) | 2023.08.25 |
---|---|
LeetCode 121. Best Time to Buy and Sell Stock (0) | 2023.08.25 |
LeetCode 169. Majority Element (0) | 2023.08.25 |
LeetCode 80. Remove Duplicates from Sorted Array II (0) | 2023.08.25 |
LeetCode 26. Remove Duplicates from Sorted Array (0) | 2023.08.24 |