zoukankan      html  css  js  c++  java
  • 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).

  • 相关阅读:
    Mysql group_concat
    canvas toDataUrl 跨域问题
    Svg操作
    java 判断浏览器
    排序操作
    java 格式判断
    你真的了解 console 吗
    svg转换工具
    java图片缩放
    常见 银行贷款 名词
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5469067.html
Copyright © 2011-2022 走看看