[LeetCode] [Array] Delete the repeated elements in the ordered sequence

Question:

Given a sorted array nums, delete duplicates in place so that each element appears only once and returns a new length.

Claim:

Do not allocate additional space for another array, you must do this by using O (1) extra memory to modify the input array in-place.

Answer1:

def removeDuplicates(nums):
    if len(nums) == 0: return 0

    nums.sort () # #sort   , in this question shenglue 
    num_pre = nums [0]
     for i in range (1 , len (nums)):
         if nums [i] -num_pre == 0:
            nums[i] = None
        else:
            num_pre = nums[i]
    while None in nums:
        nums.remove(None)
    return len(nums)

After sorting the array, compare each pair, the duplicate elements are assigned to None, and finally removed.

 

Answer2:

def removeDuplicates(nums):
    nums = set(nums)
    nums = list(nums)
    nums.sort()
    return(len(nums))

Use set properties (without duplicate elements) to delete duplicate elements.

ps: I have always reported errors when submitting answers, but I did not find out the errors?

 

Answer3:

def removeDuplicates(nums):
    if len(nums) == 0: return 0
    i = n = 0
    for j in range(1,len(nums)):
        if nums[i] != nums[j]:
            i = j
            n += 1
    return n+1,nums

According to the answer written in the prompt, it seems that you can only get the number of elements, not nums that do not contain duplicate elements. This is also welcome for discussion and correction!

 

 

——The former little boy is now big and round 

 

Guess you like

Origin www.cnblogs.com/jialinliu/p/12760042.html