Leetcode 26 Remove Duplicates

Leetcode 26 Remove Duplicates

题目描述

Remove Duplicates from Sorted Array
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 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 new length.

解题思路

此题亦可以使用插空法,即插入到正确的位置。具体来说的话,当遍历到的元素和插空前的元素进行比较,如果不等于,直接插入,如果相等,则跳过即可。

代码实现

C++版本

class Solution {
public:
    int removeDuplicates(vector& nums) {
        int len_nums = nums.size();

        if (len_nums <= 0) {
            return 0;
        }

        int insert_pos = 1;
        int i = 1;

        while (i < len_nums) {
            if (nums[i] != nums[insert_pos - 1]) {
                nums[insert_pos++] = nums[i++];
            }

            else {
                ++i;
            }
        }

        return insert_pos;
    }
};

Java版本

public class Solution {
    public int removeDuplicates(int[] nums) {
       int len = nums.length;
       if (len <= 0) {
            return 0;
       }

       int i = 1;
       int insert_pos = 1;

       while (i < len) {
            if (nums[i] != nums[insert_pos - 1]) {
                nums[insert_pos++] = nums[i++];
            }

            else {
                ++i;
            }
       }

       return insert_pos;
    }
}

Python版本

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        len_nums = len(nums)
        if len_nums <= 0:
            return 0

        insert_pos = 1
        i = 1

        while i < len_nums:
            if nums[i] != nums[insert_pos - 1]:
                nums[insert_pos] = nums[i]
                insert_pos += 1
                i += 1

            else:
                i += 1

        return insert_pos

你可能感兴趣的:(Leetcode)