zoukankan      html  css  js  c++  java
  • leetcode 【 Remove Duplicates from Sorted Array 】python 实现

    题目

    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 A = [1,1,2],

    Your function should return length = 2, and A is now [1,2].

    代码:oj测试通过 Runtime: 143 ms

     1 class Solution:
     2     # @param a list of integers
     3     # @return an integer
     4     def removeDuplicates(self, A):
     5         if len(A) == 0:
     6             return 0
     7         
     8         curr = 0
     9         for i in range(0, len(A)):
    10             if A[curr] != A[i] :
    11                 A[curr+1],A[i] = A[i],A[curr+1]
    12                 curr += 1
    13         return curr+1

    思路

    首先排除长度为0的special case

    使用双指针技巧:用curr指针记录不含有重复元素的数据长度;另一个指针i从前往后走

    Tips: 注意curr是数组元素的下标从0开始,所以再最后返回时要返回curr+1

  • 相关阅读:
    第二阶段个人冲刺总结01
    软件工程学习进度表13
    软件工程学习进度表12
    个人博客(09)
    个人博客(07)
    个人博客(08)
    poj1562 DFS入门
    poj3278 BFS入门
    数组单步运算
    十天冲刺
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4229813.html
Copyright © 2011-2022 走看看