배열다루기 - Rotate Array(배열 회전시키기)
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?
===== 풀이 _ 풀어가는중.
public void rotate(int[] nums, int k) {
int len = nums.length; //받아온 배열의 크기
int bowl[] = new int[len-k]; //분리할 부분
for(int i=0;i
if(i<len-k){
bowl[i] = nums[i]; //분리할 부분을 그릇에 담아 놓는다.
}
if(i<k){
nums[i] = nums[len-k+i]; // i번째 부터 분리된 부분 끝까지.
}else{
nums[i] = bowl[i-k]; //나머지 분리한 부분을 셋팅.
}
}
System.out.print(Arrays.toString(nums));
}
==> 해당 예제를 풀면서 Example 1 만족하는 결과를 얻게되어 기뻤지만, Example 2 도 수행해야함을 늦게 알게 되었다. 시간될 때 이어서 푸는걸로 , 일단 하나의 포문으로 해결 할 수 있다고 판단되어 위처럼 알고리즘 진행. 이후 k의 값과 len의 길이가 변화된다는 점을 참고하여 풀어나가야할듯 보인다.