My perfect Java code O(1) 1ms use reverse


  • 26
    public class Solution {
        public void reverse(int[] nums, int l, int r) {
    		while (l < r) {
    			int temp = nums[l];
    			nums[l++] = nums[--r];
    			nums[r] = temp;
    		}
    	}
    
    	public void rotate(int[] nums, int k) {
    		int n = nums.length;
    		k = (n == 0 ? 0 : k % n);
    		reverse(nums, 0    , n - k);
    		reverse(nums, n - k, n    );
    		reverse(nums, 0    , n    );
    	}
    }

  • 0
    H

    can't deal with the case: nums = []


  • 0

    Thx for ur advice. If u input [], the expected answer shows that Line 12: java.lang.ArithmeticException: / by zero. So the correct code also can't deal with the case.


  • 3
    L

    This is actually O(2*N) = O(N),because you iterate the array exactly twice


  • 0

    The hint is ”Could you do it in-place with O(1) extra space?“
    My O(1) is about space not time.


  • 0
    A

    O(2*N) is still O(n).


Log in to reply
 

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