728x90
문제
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and 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: [-1,-100,3,99] and 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]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
k번 배열을 땡기면? 된다.
맨끝 element를 배열의 제일 처음으로 가져오는걸 1번으로 친다.
그냥 한번 할 때마다 배열의 끝을 배열의 앞으로 넘기는 함수를 만들어서 k번 반복하게 구현하였다.
import java.util.*;
class Solution {
public void rotate(int[] nums, int k) {
int[] numbers = new int[nums.length];
for(int i = 0 ; i < k ; i++){
nums = change(nums);
}
System.out.println(Arrays.toString(nums));
}
public int[] change(int[] nums){
int[] numbers = new int[nums.length];
int endIndex = nums.length-1;
for(int i = 0 ; i < numbers.length ; i++){
if(i == endIndex){
numbers[0] = nums[endIndex];
}else{
numbers[i+1] = nums[i];
}
}
return numbers;
}
}
stdout 은 확인 해보면 답처럼 나오는데 왜 output은 안바뀌는거지;;
nums배열을 사용했는데...?
728x90
'Algorithm > LeetCode' 카테고리의 다른 글
Leetcode - 226 . Invert Binary Tree (0) | 2020.04.20 |
---|---|
Leetcode - 205. Isomorphic Strings (1) | 2020.04.17 |
Leetcode - 371 . Sum of Two Integers (0) | 2020.04.14 |
Leetcode - 108 . Convert Sorted Array to Binary Search Tree (0) | 2020.04.10 |
Leetcode - 88 . Merge Sorted Array (0) | 2020.04.10 |
댓글