-
배열_LeetCode_Rotate Array알고리즘/알고리즘 문제풀이 2021. 8. 30. 18:25
https://leetcode.com/problems/rotate-array/submissions/
Rotate Array - 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가 nums.count를 넘길 경우, nums.count가 의미없이 한 번 회전하므로, k % nums.count를 통해, 몇 번 이동 할 지 결정
- 결정된 range와 nums.suffix(from: ) 을 사용하여, 이동 할 요소 결정.
- 이동할 요소의 수 만큼 nums 에서 제거.
- moves 를 insert 한 뒤 종료.
정답 코드
Runtime: 348 ms, faster than 40.87% of Swift online submissions for Rotate Array.
Memory Usage: 21.4 MB, less than 74.93% of Swift online submissions for Rotate Array.
더보기class Solution { func rotate(_ nums: inout [Int], _ k: Int) { let range = k % nums.count == 0 ? k : k % nums.count let moves = nums.endIndex - range <= 0 ? nums.suffix(from: 0) : nums.suffix(from: nums.endIndex - range) for _ in 0..<moves.count { if nums.isEmpty != true { nums.removeLast() } } nums.insert(contentsOf: moves, at: 0) print(nums) } }
'알고리즘 > 알고리즘 문제풀이' 카테고리의 다른 글
순열_LeetCode_permutation-in-string (0) 2021.09.08 이진트리_LeetCode_binary-search (0) 2021.09.02 큐_LeetCode_find-the-winner-of-the-circular-game (0) 2021.08.26 해쉬_Leetcode_rabbits-in-forest (0) 2021.08.25 DFS/BFS 백트랙킹_백준_15649 (0) 2021.08.24