Skip to content

Instantly share code, notes, and snippets.

@vicradon
Created May 9, 2024 20:20
Show Gist options
  • Save vicradon/a155f9f174ddd74d7345441adbcb91a3 to your computer and use it in GitHub Desktop.
Save vicradon/a155f9f174ddd74d7345441adbcb91a3 to your computer and use it in GitHub Desktop.
Leetcode grind
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
'''
while right pointer > left pointer
- check through from the right pointer
- move cursor to the left if the number there equals target
- else check through from the left pointer
- if number equals target, swap the left with the right
- move the left forward
- else move the left forward
2
[0,1,2,2,2,2,4,2]
l
r
[2, 2, 3, 3]
l
r
'''
if len(nums) == 0:
return 0
count, l = 0, 0
for r in range(len(nums)):
if nums[r] != val:
nums[l] = nums[r]
l += 1
else:
count += 1
return len(nums) - count
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# trivial solution
'''
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
'''
# efficient solution
hashmap = dict()
for i in range(len(nums)):
othernum = target - nums[i]
if othernum in hashmap:
return [i, hashmap[othernum]]
else:
hashmap[nums[i]] = i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment