I am working on the problem removeDuplicatesFromSortedList
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length.
My solution and TestCase
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
"""
"""
#Base Case
if len(nums) < 2: return len(nums)
#iteraton Case
i = 0 #slow-run pointer
for j in range(1, len(nums)):
if nums[j] == nums[i]:
continue
if nums[j] != nums[i]: #capture the result
i += 1
nums[i] = nums[j] #in place overriden
return i + 1
class MyCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test_raw1(self):
nums = [1, 1, 2]
check = self.solution.removeDuplicates(nums)
answer = 2
self.assertEqual(check, answer)
def test_raw2(self):
nums = [0,0,1,1,1,2,2,3,3,4]
check = self.solution.removeDuplicates(nums)
answer = 5
self.assertEqual(check, answer)
unittest.main()
This runs but I get a report:
Runtime: 72 ms, faster than 49.32% of Python3 online submissions for Remove Duplicates from Sorted Array. Memory Usage: 14.8 MB, less than 5.43% of Python3 online submissions for Remove Duplicates from Sorted Array.
Less than 5.43%, I employ the in-place strategies but get such a low rank, how could improve it?