Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
从链表中删除重复结点,这题非常类似于 Remove Duplicates from Array,只是链表操作中还需要重新定义指向问题。维护一个prev为重复元素的开始元素,cur为当前处理的元素。当前为重复元素时,就令prev.next=cur.next。否则更新prev,代码如下:
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ length=len(nums) if length<3: return length end = 1 for i in xrange(2,length): temp = nums[i] if temp != nums[end-1] : end+=1 nums[end]=temp return end+1
时间复杂度O(n),空间复杂度O(1).
posted on 2016-05-07 20:14 Sheryl Wang 阅读(92) 评论(0) 编辑 收藏 举报