My accepted Java code


  • 0
    J
     public class Solution {
        	public static void main(String [] args){
        		int []a=new int[]{1,2};
        		rotate(a,2);
        		System.out.println(a[0]+" "+a[1]);
        		
        	}
            public static void rotate(int[] nums, int k) {
                if(k<nums.length){
                reverse(nums,0,nums.length-1);
                reverse(nums,0,k-1);
                reverse(nums,k,nums.length-1);
                }else if(k==nums.length){
                    
                }else{
                    k=k%nums.length;
                    rotate(nums,k);
                }
            }
             public static void reverse(int[] nums,int i,int j){//给定边界转置数组
                    while(i<=j&&nums.length>1){
                        int temp=nums[j];
                        nums[j]=nums[i];
                        nums[i]=temp;
                        i++;
                        j--;
                    }
                }
        }

  • 0
    S

    算法和你的基本上差不多
    rotate里面怎么不这样写 k %= nums.length ?

    另外,你运行的结果是什么样的


  • 0
    4
        int n = nums.length;
    	k %= n;
    	reverse(nums,0,n-k-1);
    	reverse(nums,n-k,n-1);
    	reverse(nums,0,n-1);

Log in to reply
 

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