Home > Net >  C# - leetcode 189, array hasn't changed
C# - leetcode 189, array hasn't changed

Time:06-25

The problem is as follows:

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: nums = [1,2,3,4,5,6,7], 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]

My code:

public class Solution 
{
    public void Rotate(int[] nums, int k) 
    {
        List<int> list = nums.ToList();
        
        for (int i = 0; i < k; i   )
        {
            int first = nums[0];
            list.RemoveAt(0);
            list.Add(first);
        }
        
        nums = list.ToArray();
    }
}

And I got a wrong answer as follows:

Wrong Answer
Runtime: 156 ms
Your input
[1,2,3,4,5,6,7]
3
Output
[1,2,3,4,5,6,7]
Expected
[5,6,7,1,2,3,4]

My question:

I assign the adjusted list to nums but why it hasn't changed?

CodePudding user response:

Objects in C# are reference types, but they're passed by value.

Imagine if I gave you a box. You're welcome to do whatever you want with the contents, and when I return to collect the box I keep whatever you've put in it.

However, if you decide to replace my box with a new box, and you put things in the new box, then I don't get those things when I come back to collect the original box I gave to you.

When you call

nums = list.ToArray();

you are discarding the nums that was passed to you and you are replacing it with something else. That replaced value does not leave the function. The leetcode script that called your function checks the original nums object (box) and finds its contents unchanged.

Try doing the following instead of the assignment expression I mentioned above:

for(int i=0; i<list.Count(); i  )
{
    nums[i] = list[i];
}

Here you're modifying the contents of nums without changing the object.

CodePudding user response:

I assign the adjusted list to nums but why it hasn't changed?

nums is a regular parameter, and as such is passed by value. Any changes you make to its handle (like assigning to it) won't be visible to the array passed in from the outside.

So either replace the items in the array given to you one by one, or pass the array parameter by reference (ref int[] nums).

As an aside, your solution is incredibly bad. You took what should have been a time-linear and memory-constant solution and made a time-quadratic monstrosity that allocates two entire needless arrays.

  • Related