Catalogue
Same Direction
27. Remove Element
- left pointer represents the postion that next valid result will be put in!!
1
2
3
4
5
6
7
8
9# Time : O(n), Sapce : O(1)
class Solution(object):
def removeElement(self, nums, val):
left = 0
for i in range(len(nums)):
if nums[i] != val:
nums[left] = nums[i]
left += 1
return left
26. Remove Duplicates from Sorted Array
- first pointer represents the last position in the result!
1
2
3
4
5
6
7
8
9
10
11
12# Time : O(n), Sapce : O(1)
class Solution(object):
def removeDuplicates(self, nums):
if not nums:
return 0
first = 0
for i in range(1, len(nums)):
if nums[i] != nums[first]:
first += 1
nums[first] = nums[i]
return first+1
80. Remove Duplicates from Sorted Array II
- small trick: 1. start interation from index 2, 2. comprare with the element with only the second last element!
1
2
3
4
5
6
7
8
9
10
11
12
13# Time : O(n), Sapce : O(1)
class Solution(object):
def removeDuplicates(self, nums):
n = len(nums)
if n <= 2:
return n
first = 1
for i in range(2, n):
if nums[i] != nums[first-1]:
first += 1
nums[first] = nums[i]
return first + 1
Two Sequence
88. Merge Sorted Array
- two pointers
1 | class Solution: |