26. Remove Duplicates from Sorted Array [remove duplicates sorted array]

Description
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.

Examples of
Here Insert Picture Description
ideas

  • That is to delete the place, in fact, not deleted, just not the same few numbers are on the front of the location, and leave behind

answer

  • python
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if len(nums)==0: return 0
        i=0
        for j in range(len(nums)):
            if nums[j]!=nums[i]:
                i+=1
                nums[i]=nums[j];
        return i+1
  • java
class Solution {
    public int removeDuplicates(int[] nums) {

        int i=0;
        for(int n:nums)
            if (nums[i]<n)
                nums[++i]=n;
        return i+1;
    }
}
  • c++
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size()==0) return 0;//可能由于c++不管数组是不是越界,当数数组为空是,返回1,不检测是不是越界,故而会出现问题
        int real = 0;
        for (int n: nums)
            if (n!=nums[real])
                nums[++real]=n;
        return real+1;
        
    }
};
Published 78 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/puspos/article/details/103151622