每天刷LeetCode——D2【简单题】

题目编号:

0026.remove-duplicates-from-sorted-array

题目描述:

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 returned length. Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

算法思路:

1)对一个数组设置两个索引,分别为快索引和慢索引,快索引多走一步
2)如果快索引和慢索引对应元素相等,快索引往前走一步,慢索引不动
3)如果快慢索引对应元素不同,慢索引往前走一步,快索引对应元素给慢索引,快索引往前走一步
4)重复2、3步骤

算法实现

# =============================================================================
#算法实现 
# =============================================================================
class Solution:
    def removeDup(self,s):
        slow_index=0
        fast_index=1

        for i in range(len(s)):
            #遇到快慢指针不相等的情况
            if fast_index < len(s) and s[slow_index]!=s[fast_index]:
                slow_index+=1
                s[slow_index]=s[fast_index]
                fast_index+=1
            #快慢指针相同
            elif fast_index < len(s):
                fast_index+=1
        return slow_index+1,s[:slow_index+1]
#测试
test=Solution()
length,s=test.removeDup(list('122344556'))
                

你可能感兴趣的:(LeetCode刷题,LeetCode)