题目链接
https://leetcode.com/problems/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.
题目翻译
给定一个有序数组,直接在数组中删除重复元素,使每个元素只出现一次,并返回长度。不允许申请额外空间存放另一个数组,你只能使用O(1)空间复杂度在原数组操作。
比如,给定数组nums = [1,1,2],你的函数应该返回2,同时数组nums的前两个元素是1和2。在数组长度之外的值是多少无所谓。
思路方法
思路一
用两个指针,一个指针用于扫描遍历整个列表,另一个指针始终指向下一个数字要写入列表的位置。效果相当于在遍历列表的时候,将不同的数字重新写入到原数组。
代码
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
cur = 0
for i in range(1, len(nums)):
if nums[i] != nums[cur]:
cur += 1
nums[cur] = nums[i]
return cur+1
思路二
用一个计数器记录当前有多少个重复数字,以此来决定下一个要写入数组的数字的位置,以及当遍历完数组时得到新数组的长度。
代码
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
for i in range(1, len(nums)):
if nums[i] == nums[i-1]:
count += 1
else:
nums[i-count] = nums[i]
return len(nums) - count
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51589013

本文介绍了解决LeetCode上一道经典题目的两种方法:通过双指针技巧和计数器技巧来删除排序数组中的重复元素,使得每个元素只出现一次,且必须在原地操作以达到O(1)的空间复杂度。
982

被折叠的 条评论
为什么被折叠?



