首页 > 代码库 > LeetCode 26. Remove Duplicates from Sorted Array

LeetCode 26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn‘t matter what you leave beyond the new length.

 

Subscribe to see which companies asked this question.

题目大意:给定一个有序数组,删除重复元素,返回新的数组的长度。不为另一个数组分配额外空间,必须用常量内存做到这一点。
解题思路:遍历数组,如果遇到跟前一个元素相同的元素就跳过,遇到不重复的元素则将count加1.原本以为只要统计新数组长度就行了,结果一直报错。原来还要删除元素后数组要按新的元素排列才行。因此修改了一下代码。原本python很方便的可以用for i in nums[1:]这种方式遍历数组的所有值,现在只能够用下标的方式遍历。
技术分享

 

class Solution(object):
  def removeDuplicates(self, nums):
  """
  :type nums: List[int]
  :rtype: int
  """
  count = 1
  index = 1
  if len(nums) <= 1:
    return len(nums)
  for i in range(1,len(nums)):
  if(nums[i] != nums[i - 1]):
    nums[index] = nums[i]
    count += 1
    index += 1
  return count

 
 

LeetCode 26. Remove Duplicates from Sorted Array