일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 비트연산자
- JavaScript
- TypeScript
- leetcode
- programmers
- 정규표현식
- 디자인
- 알고리즘
- 웹접근성
- wai-aria
- 카드뉴스
- 제로베이스 프론트엔드 스쿨
- html&css
- react-query
- 프로그래머스
- react
Archives
- Today
- Total
記錄
[JS]189. Rotate Array 본문
문제 링크: https://leetcode.com/problems/rotate-array/
난이도: Medium
Given an array, rotate the array to the right by k steps, where k is non-negative.
주어진 배열을 음수가 아닌 정수 k만큼 우측으로 회전시켜라.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
- 1 <= nums.length <= 105
- 231 <= nums[i] <= 231 - 1
- 0 <= k <= 105
Follow up:
- Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
Related Topics: Array, Math, Two Pointers
문제풀이
배열 nums에서 k만큼의 요소들을 뒤에서 앞으로 위치를 바꿔주는 방법을 찾는 문제이다.
k만큼 잘라낸 부분 내에서 따로 요소들끼리 순서가 바뀌거나 하지는 않기 때문에 k만큼 splice한 부분을 nums 에 unshift하면 된다. 아니면 nums에서 k만큼을 뺀 이후 나머지를 unshift하는 방식으로 해도 된다.
var rotate = function(nums, k) {
k = k % nums.length; //if k > nums.length , k%=nums.length로 적어도 됨
let rotate=nums.splice(nums.length-k);
return nums.unshift(...rotate);
// nums.unshift(...nums.splice(nums.length-k)); //한줄 버전
};
'FRONTEND STUDY > LeetCode' 카테고리의 다른 글
[JS] 386. Lexicographical Numbers (0) | 2022.10.20 |
---|---|
[JS]2418. Sort the People (0) | 2022.10.19 |
[JS] 34. Find First and Last Position of Element in Sorted Array (1) | 2022.10.14 |
[JS] 136. Single Number (0) | 2022.10.12 |
[JS] 215. Kth Largest Element in an Array (0) | 2022.10.11 |
Comments