banner
biuaxia

biuaxia

"万物皆有裂痕,那是光进来的地方。"
github
bilibili
tg_channel

Leetcode-01-Remove Duplicates from Sorted Array

title: Leetcode-01-Remove Duplicates from Sorted Array
date: 2022-02-12 22:23:13
toc: true
category:

  • leetcode
    tags:
  • leetcode
  • remove
  • duplicates
  • sorted
  • array

The problem is solved using two pointers (slow pointer and fast pointer). The fast pointer represents the index position being traversed in the array, and the slow pointer represents the index position where the next different element should be filled in. Initially, both pointers point to index 1.

The problem statement states that the input array nums is sorted in ascending order.

Assuming the length of nums is n, the fast pointer fast traverses from 1 to n-1. For each position,

If nums[fast] != nums[fast-1], it means nums[fast] is different from the previous element.

Therefore, move nums[fast] to the position of nums[slow], and then increment the value of slow by 1 to point to the next position.

After the traversal, the elements from nums[0] to nums[slow-1] are all different and contain every different element from the original array. Therefore, the length of the new array is slow, and we can return slow.

func removeDuplicates(nums []int) int {
	if 0 == len(nums) {
		return 0
	}

	slow := 1
	for fast := 1; fast < len(nums); fast++ {
		if nums[fast] != nums[fast-1] {
			nums[slow] = nums[fast]
			slow++
		}
	}
	return slow
}

image.png

References#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.