每天一道面试题--删除排序数组中的重复项(python实现)

题目1:给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

示例 1:

给定数组 nums = [1,1,2], 

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 

你不需要考虑数组中超出新长度后面的元素。

示例 2:

给定 nums = [0,0,1,1,1,2,2,3,3,4],


函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。

你不需要考虑数组中超出新长度后面的元素。



解答:
'''
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].
'''

# Remove Duplicates from Sorted Array
# 时间复杂度O(n),空间复杂度O(1)
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if nums == "":
            return False

        i = 0
        while i < len(nums) - 1:
            if nums[i] == nums[i + 1]:
                nums.remove(nums[i])
            else:
                i = i + 1
        return len(nums)
 

测试代码:

if __name__ == "__main__":
    A = [1, 1, 2]
    B = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
    C = []
    s = Solution()
    A_len = s.removeDuplicates(A)
    B_len = s.removeDuplicates(B)
    C_len = s.removeDuplicates(C)
    print(A_len)
    print(A)
    print(B_len)
    print(B)
    print(C)
    print(C_len)

测试结果:

2
[1, 2]
5
[0, 1, 2, 3, 4]
[]
0
 

猜你喜欢

转载自www.cnblogs.com/yuzhou-1su/p/11650832.html