Skip to content

Instantly share code, notes, and snippets.

@PatrickVienne
Created October 15, 2023 15:04
Show Gist options
  • Save PatrickVienne/2cbb18a26d840c9db031ca2634a8e2a6 to your computer and use it in GitHub Desktop.
Save PatrickVienne/2cbb18a26d840c9db031ca2634a8e2a6 to your computer and use it in GitHub Desktop.
leetcode_27_remove_element.go
// https://leetcode.com/problems/remove-element/description/
func removeElement(nums []int, val int) int {
if len(nums) == 0 {
return 0
}
writeptr := len(nums)-1
readptr := 0
// replace val with number from the back
// on each replace move the writeptr one to the front
for ; readptr<writeptr;readptr++ {
if nums[readptr]==val {
nums[readptr] = nums[writeptr]
writeptr--
// have to retry again, so reset readptr,
// as it is incremented each iteration
readptr--
}
}
// if iteration stopped pointing on the searched val
if readptr==writeptr && nums[readptr]==val {
return readptr
}
return readptr+1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment