본문 바로가기
Algorithm/LeetCode

Leetcode - 189 . Rotate Array

by HaningYa 2020. 4. 14.
728x90

 

[Must do Easy Question]

 

How to effectively use LeetCode to prepare for interviews!! - LeetCode Discuss

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

 

 

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


문제

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배열을 사용했는데...?

 

 

 

Rotate Array

249218 views so far on LeetCode Articles

leetcode.com

 

728x90

댓글