Some one can give me a solution


  • 0
    J

    public class Solution {
    public void rotate(int[] nums, int k) {
    if(nums==null||k>nums.length){

         return;
     }
     revers(nums,0,nums.length-1);
     revers(nums,0,k-1);
     revers(nums,k,nums.length-1);
    }
    
    int[] revers(int[] nums, int start,int end){
        while(start<end){
           int temp=nums[start];
    		nums[start]=nums[end];
    		nums[end]=temp;
    		start++;
    		end--;  
            
        }
        return nums;
    }
    

    }

    this is my code.
    but after submit ,
    Input:
    [1,2], 3
    Output:
    [1,2]
    Expected:
    [2,1]

    it assume k=3 ,but the length of array is 2, it should't rotate .
    but why the expected is [2,1]


  • 0

    Given: [1,2]
    Rotated one step to the right: [2,1]
    Rotated two steps to the right: [1,2]
    Rotated three steps to the right: [2,1]


  • 0
    M
     k=k%n; will solve the issue. 
    because when length = 2 and k= 3. then k=k%n ==> k=3%2 ==> 1.
    Hence the array is rotated once

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.