第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