For the task:
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.
I wrote a following solution:
for value in nums[:]:
if value == val:
nums.remove(value)
return len(nums)
However, the solution seems to be ineffective due to the time and space complexity. The question is if I am estimating it correctly.
- So, for the creation of the array cope
nums[:]
the complexity is O(n) - We iterate through each element of the array once: O(n)
The resulting time complexity will be O(n^2) with space complexity O(n), or?
Thanks in advance for the comments and input!