Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
•
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
•
Return k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
Plain Text
복사
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Plain Text
복사
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
Plain Text
복사
Constraints:
•
0 <= nums.length <= 100
•
0 <= nums[i] <= 50
•
0 <= val <= 100
When reading the problem, it seems to be asking us to remove the value that comes in as the parameter val if it exists in the nums array. Looking at the last explanation in Example 2, it says that after removing the val from the nums array, the order of the elements doesn’t matter. So I thought maybe I could simply replace the val values with _.
First Try
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
answer = []
hit_count = 0
for i in range(len(nums)):
if nums[i] == val:
hit_count += 1
else:
answer.append(nums[i])
answer += ['_'] * hit_count
return answer
Python
복사
The variable answer is a list used to store the return value, and hit_count increases by 1 each time an element in the nums array matches the value val.
After that, while looping, if the element matches val, hit_count is incremented. otherwise, the element is appended to the answer list as is.
When the loop ends, a number of underscores ('_') equal to hit_count are appended to the end of the answer list. For example, if hit_count is 3, then '_', '_', '_' are appended.
When I ran the test case, a Runtime Error occurred. The error message indicated that the function was expected to return an int, but I was returning an array instead. This happened because my initial approach to the problem was wrong, and it was ultimately a mistake caused by my carelessness in not reading the problem carefully.
Upon rereading the problem statement, I realized that it clearly explained the evaluation process. According to the criteria, the return value should be an int k, not an array, and the judge only considers the first k elements of the modified nums array.
Then, it performs sort(nums, 0, k) to sort those elements and compares them with the expected answer (expectedNums). Therefore, what I need to return is simply the number of elements that are not equal to val. The order of the first k elements in nums does not matter, since the evaluation process already sorts them before comparison.
Therefore, to solve the problem, only two steps are required. First, determine the number of elements in the array that are not equal to val (this will be k). Second, iterate through the array and place each non-val element sequentially from the beginning. By doing this, the evaluation process will validate only the first k elements of nums, and the solution will be considered correct.
Second Try
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for v in nums:
if v != val:
nums[k] = v
k += 1 #
return k
Python
복사
The code I wrote above is based on re-reading and understanding the problem. As explained earlier, the function simply performs the two tasks and then returns k. Now, I will run the test cases again.
Fortunately, the test cases passed successfully. Now, I will go ahead and submit my solution.
The solution was accepted! In fact, this problem would have been very simple to implement if I had just understood the statement correctly.
However, I rushed through reading it, made assumptions on my own, and ended up writing a completely wrong solution that was far from the correct answer.
Through this experience, I realized once again that while understanding and implementing various algorithms is important, it is just as crucial to carefully read and fully understand the problem before writing any code.
Since I am still at the beginner stage of learning coding tests, I should make it a habit not to rush when reading problems and only start coding once I truly feel confident that I have understood them.