8. The algorithm is simple and swift remove duplicates sort array

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huanglinxiao/article/details/91453260

Given a sorted array, you need to remove the recurring elements in place, so that each element appears only once, after returning the new length of the array is removed.

Do not use extra space for an array, you must modify the input array in place and completed under the conditions of use O (1) extra space.

Example 1:

Given array nums = [1,1,2], 

Function should return a new length of 2, and the first two elements of the original array is modified to nums 1, 2. 

You do not need to consider beyond the elements of the new array length behind.
Example 2:

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

New function should return the length 5 and the first five elements of the original array nums is modified to 0, 1, 2, 3, 4.

You do not need to consider beyond the elements of the new array length behind.

 

solution:

 func removeDuplicates(_ nums: inout [Int]) -> Int {
        guard nums.count > 0 else {
            return 0
        }
       
        var indexa = 0
        
        for (index,value) in nums.enumerated().reversed() {
          
            if index - 1 < 0{
                break
            }
            if(nums[index] == nums[index-1]){
                indexa += 1
                nums.remove(at: index)

            }
            
        }
        
        return nums.count;
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/91453260