第1.2节 排序数组去重

创建于 20170308
原文链接:
https://leetcode.com/problems/remove-duplicates-from-sorted-array/?tab=Description

1 题目:

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.

2 python 代码:

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

3 算法解析

这是一个典型的双指针问题。i是慢指针,j是快指针。
找到不重复的进行swap即可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • leetcode刷题记录本文记录一下leetcode刷题记录,记录一下自己的解法和心得。 LeetCode Two...
    EarthChen阅读 3,504评论 0 6
  • 326. Power of Three Given an integer, write a function to...
    跑者小越阅读 2,157评论 0 1
  • 总结了一下自己以往混沌的生活,突然想重新开始~ 今日早上6:30起床,希望能坚持早起~能坚持写晨间日记~每日能早上...
    插画姐阅读 118评论 0 1
  • 文/青山若夫 前几日,单位组织年度培训,某著名高校的导师在课堂上抛出一个问题:“假如碰到老人摔倒了,你会马上去扶吗...
    青山若夫阅读 1,152评论 39 37