Problem overview
The method FirstN receives a List<int> named nums and a number n. It returns a new list holding the first n numbers of nums, in the same order. When n is 0, the result is an empty list.
For nums = [3, 8, 1, 9, 4] and n = 3, the result is [3, 8, 1]: the 9 and the 4 are left out. For [5, 6, 7] and n = 0 nothing is taken, so the result is empty. For [2, 4] and n = 2, every number is kept. The constraints promise that n is between 0 and the length of nums, so you never have to ask for more numbers than exist.
Approach
The first n numbers are a slice that starts at index 0 and is n long. A List<T> already has a method for copying such a slice: GetRange(start, count). It takes a start index and a count, not an end index, so the call is nums.GetRange(0, n). No loop is needed.
The result is a new list. That matters here, because the task says to return a list with the numbers, not to cut down nums itself. After the call, nums still has all its numbers.
Step by step
- Copy the slice. Call
GetRangeonnumswith the start index 0 and the countn, and store the new list in aList<int>namedresult. Withn = 0, the count is zero and the list is empty. - Return
result.
The solution in C#
class Solution {
public List<int> FirstN(List<int> nums, int n) {
List<int> result = nums.GetRange(0, n);
return result;
}
}
Running it on the three examples prints these lists, with the numbers separated by spaces (an empty list prints nothing):
3 8 1
2 4
The C# details worth knowing:
- Count, not end index.
GetRange(0, n)copiesnitems. Because the start is 0 the two readings give the same result here, but for a start other than 0 they do not. - A shallow copy. For a list of
intthe copy is completely independent: changingresultlater does not touchnums. - An empty result is a real list.
GetRange(0, 0)returns an emptyList<int>, notnull, so the caller can useCountand loops on it safely. - No clamping. C# does not shorten an oversized request. On
[2, 4],GetRange(0, 3)throws anArgumentException. The constraints keepnwithin the length, so this lesson never hits it, but in a program of your own you would useMath.Min(n, nums.Count)as the count.
Edge cases and common mistakes
nequal to 0. The result is empty, and the code needs no special case.nequal to the length. Every number is copied, and the result equalsnums.- Using
nas an end index. That is correct only when the start is 0, which is the case here. Keep the habit anyway: the second argument is how many items. - Returning
numsitself. That would return all the numbers instead of the firstn. - Removing the extra numbers from
nums. It also changes the list the caller passed in. Copying leaves it alone.
Testing
[3, 8, 1, 9, 4],n = 3gives[3, 8, 1].[5, 6, 7],n = 0gives[].[2, 4],n = 2gives[2, 4].[7],n = 1gives[7].
