返回

通过简单步骤轻松解决 LeetCode 第 26 题:删除有序数组中的重复项

后端

def removeDuplicates(nums):
  """
  Removes duplicate elements from an ordered array.

  Args:
    nums: The array to remove duplicates from.

  Returns:
    The length of the array after duplicates have been removed.
  """

  # If the array is empty, there are no duplicates to remove.
  if not nums:
    return 0

  # Initialize the index of the next unique element.
  next_unique = 1

  # Iterate over the array, starting from the second element.
  for i in range(1, len(nums)):
    # If the current element is different from the previous element, it is unique.
    if nums[i] != nums[i - 1]:
      # Move the unique element to the next unique index.
      nums[next_unique] = nums[i]
      # Increment the index of the next unique element.
      next_unique += 1

  # Return the length of the array after duplicates have been removed.
  return next_unique


# Test the function.
nums = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
print(removeDuplicates(nums))  # Output: 5
nums = []
print(removeDuplicates(nums))  # Output: 0
nums = [1]
print(removeDuplicates(nums))  # Output: 1

继续打卡算法题,今天学习的是LeetCode的第26题删除有序数组中的重复项,这道题目是道简单题。算法题的一些解题思路和技巧真的非常巧妙,每天看一看算法题和解题思路,对我们的编码思维和编码能力有帮助。

LeetCode 第 26 题:删除有序数组中的重复项

题目
给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素只出现一次,返回删除后数组的新长度。

示例:
输入:[1,1,2,2,3,3,4,4,5,5]
输出:5

def removeDuplicates(nums):
  if not nums:
    return 0

  next_unique = 1

  for i in range(1, len(nums)):
    if nums[i] != nums[i - 1]:
      nums[next_unique] = nums[i]
      next_unique += 1

  return next_unique


nums = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
print(removeDuplicates(nums))  # Output: 5

nums = []
print(removeDuplicates(nums))  # Output: 0

nums = [1]
print(removeDuplicates(nums))  # Output: 1

Python 算法解析:

  1. 定义 removeDuplicates 函数,接受有序数组 nums 作为参数。
  2. 检查数组是否为空,如果是,则返回 0,因为没有重复元素需要删除。
  3. 初始化一个变量 next_unique,用于跟踪下一个唯一元素的索引。
  4. 从数组的第二个元素开始遍历,将每个元素与前一个元素进行比较。
  5. 如果当前元素与前一个元素不同,则表示它是一个唯一元素。
  6. 将唯一元素移动到下一个唯一元素的索引处。
  7. 将下一个唯一元素的索引加 1。
  8. 返回下一个唯一元素的索引,即删除重复元素后数组的新长度。
  9. 在函数外,提供三个测试用例来演示函数的运行情况。

希望通过这篇文章,您对 LeetCode 第 26 题:删除有序数组中的重复项有更深入的理解。如果您对算法题有兴趣,欢迎继续关注我们的文章,我们将为您带来更多精彩内容!