Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Table of Contents
stylenone

Remove Duplicates from Sorted Array 删除有序数组中的重复项

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

Code Block
languagego
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
}

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

Code Block
languagego
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
}

Remove Duplicates from Sorted List 删除排序链表中的重复元素

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

Code Block
languagego
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func deleteDuplicates(head *ListNode) *ListNode {
    if head == nil {
        return nil
    }
    
    slow, fast := head, head
    for fast != nil {
        if slow.Val != fast.Val {
            slow.Next = fast
            slow = slow.Next
        }
        
        fast = fast.Next
    }
    
    slow.Next = nil
    return head
}

注意:数组版本保证至少有一个元素,而链表版本并没有保证,所以链表版本的代码需要判断是否为空(否则会空指针异常)

Remove Element 移除元素

https://leetcode.com/problems/remove-element/