LeetCode26 removes duplicates in an ordered array Go language

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

insert image description here

func removeDuplicates(nums []int) int {
    
    
    n := len(nums)
    if n<2{
    
    
        return n
    }
    low := 0
    fast := 0
    for fast<n {
    
    
        if nums[low]==nums[fast]{
    
    
            fast++
        }else{
    
    
            low++
            nums[low] = nums[fast]
            fast++
        }
    }
    nums = nums[:low+1]
    return low+1
}

Ideas:

  1. Idea 1, the straightforward method I first thought of is to maintain a variable i, and then traverse backwards, if i and i-1 are the same, delete this variable as follows, if not, i++, until i>=len(nums) exits the loop. The consumption of this idea is a bit large, so it is not recommended.
nums[i] = append(nums[:i],nums[i+1:]...)
  1. The second idea is to move the different ones to the front of the array as shown in the figure, and only take the front part of the array after traversing. I used this method to submit twice. For the first n part, I used len(nums) directly, which seemed to consume a lot, so I saved the array length in n. Then it's double hundred.

Guess you like

Origin blog.csdn.net/rglkt/article/details/122484595