public int removeDuplicates(int[] nums) {
// Check for edge cases.
if (nums == null) {
return 0;
}
// Use the two pointer technique to remove the duplicates in-place.
// The first element shouldn't be touched; it's already in its correct place.
int writePointer = 1;
// Go through each element in the Array.
for (int readPointer = 1; readPointer < nums.length; readPointer++) {
// If the current element we're reading is *different* to the previous
// element...
if (nums[readPointer] != nums[readPointer - 1]) {
// Copy it into the next position at the front, tracked by writePointer.
nums[writePointer] = nums[readPointer];
// And we need to now increment writePointer, because the next element
// should be written one space over.
writePointer++;
}
}
// This turns out to be the correct length value.
return writePointer;
}
func removeDuplicates(nums []int) int {
// Check for edge cases.
if nums == nil {
return 0
}
// Use the two pointer technique to remove the duplicates in-place.
// The first element shouldn't be touched; it's already in its correct place.
var writePointer int = 1
// Go through each element in the Array.
for readPointer := 1; readPointer < len(nums); readPointer++ {
// If the current element we're reading is *different* to the previous
// element...
if nums[readPointer] != nums[readPointer-1] {
nums[writePointer] = nums[readPointer]
// And we need to now increment writePointer, because the next element
// should be written one space over.
writePointer++
}
}
// This turns out to be the correct length value.
return writePointer
}
Array 101 Sort Array By Parity (0) | 2022.03.15 |
---|---|
Array 101 Move Zeroes in Go (0) | 2022.03.10 |
Array101 Remove Duplicates from Sorted Array (0) | 2022.03.06 |
Arrays 101 Code from Java to Go(A Better Repeated Deletion Algorithm - Intro) (0) | 2022.03.06 |
Arrays101 Replace Elements with Greatest Element on Right Side in GO (2) | 2022.03.05 |
댓글 영역