Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

Remove Duplicates from Sorted Array

https://leetcode.com/problems/remove-duplicates-from-sorted-array/

func removeDuplicates(nums []int) int {
    i := 0
    j := 1
    
    for ; j < len(nums); j++ {
        if nums[j] == nums[j-1] {
            // duplicate
            continue
        }
        
        nums[i+1] = nums[j]
        i++
    }
    
    return i+1
}

另一种解法:思路类似,但是代码组织形式不同

func removeDuplicates(nums []int) int {
    slow, fast := 0, 0
    
    for fast < len(nums) {
        if nums[fast] != nums[slow] {
            slow++
            nums[slow] = nums[fast]
        }
        
        fast++
    }
    
    return slow+1
}
  • No labels