Why does my solution work wrong?

  • -2
    public class Solution {
    public void rotate(int[] nums, int k) {
        if (nums.length == 1 || nums.length < k) {
        int[] result = new int[nums.length];
        for (int i = nums.length - k, j = 0; j < nums.length; j++, i++) {
            i = i % nums.length;
            result[j] = nums[i];
        nums = result;

    I test my code in eclipse, and print the last nums' value, I think it work well.

  • 0

    When you print the last nums' value,
    it will give you correct output .

    But here , when rotate method is
    called, nums array has got its own

    When you computed the final
    values and stored it in result array,
    and did this nums=result,nums got its
    new base address and the original
    one was lost . So changes to nums will
    not affect the array which was passed as
    a parameter when calling rotate method.

    Hence it gave wrong output.

    Also ,
    if (nums.length == 1 || nums.length < k) {

    this statement is wrong because k's value
    could be any unsigned integer either less than,equal to
    or greater than nums.length.

    Assume this test-case,
    nums={10,20,30,40,50} , k=2 ,

    then the answer should be

    you can do only this instead of that if

    Hope this helps !!!

Log in to reply

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