Created
October 15, 2023 15:04
-
-
Save PatrickVienne/2cbb18a26d840c9db031ca2634a8e2a6 to your computer and use it in GitHub Desktop.
leetcode_27_remove_element.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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