Location>code7788 >text

26. Remove duplicates from an ordered array Golang implementation

Popularity:49 ℃/2024-09-19 11:20:49

Title Description:

Given a non-strictly increasing array nums, delete the recurring elements in place so that each element occurs only once, and return the new length of the array after deletion. The relative order of the elements should remain consistent. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k. You need to do the following to ensure that your solution to the problem is passable:
Change the array nums so that the first k elements of nums contain unique elements in the order in which they first appeared in nums. the remaining elements of nums are unimportant with respect to the size of nums.
Return k.

Title Analysis:

  • Input: Ordered array
  • Target: number of unique elements
  • Requirement: In-situ deletion (no change in memory address)

Since it requires in-place deletion, you can't create a new variable, and Golang's slice doesn't have a delete operation, so you can only create a new variable and assign a value if you want to delete it. So you can only overwrite the duplicate value. The operation is performed using a double pointer. The purpose of the pointer j is to find the location of the non-repeating element, when i,j point to the same element, at this time only i move backward, j does not move, because j pointer to the last non-repeating element after the current processing. When moving i to a different value than j, j moves backward, and if nums[i],nums[j] point to a different location, all the elements in between them will be duplicate elements (to be replaced).

Click to view code
func removeDuplicates(nums []int) int {
   j:=0
    for i := 0; i < len(nums); i++ {
        if nums[i]!=nums[j] {
            j++
            nums[j] = nums[i]
        }
    }
    return j+1
}