美文网首页
LeetCode 26. Remove Duplicates f

LeetCode 26. Remove Duplicates f

作者: 洛丽塔的云裳 | 来源:发表于2020-04-04 23:03 被阅读0次

0. 题目

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:
Given 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 returned length.

Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.

1. c++版本

方法1,先申请另外一个vector用来存放最终去重后的结果,依次去读取nums里面的数字如果重复,跳过

    int removeDuplicates(vector<int>& nums) {
        if (nums.empty())
            return 0;
        vector<int> result;
        int prev = nums[0];
        result.push_back(prev);
        for (int i=0, j=i+1; i<nums.size()-1;) {
            while (j<nums.size() && prev == nums[j]) {
                j++;
            }
           if (j == nums.size()) 
               break;
           prev = nums[j];
           i = j;
           j++;
           result.push_back(prev);
        }
        nums = result;
        return nums.size();
    }

方法2,思考是不是可以不用重新申请vector, 直接将去重复后的数字放到nums前面

    int removeDuplicates(vector<int>& nums) {
        if (nums.empty())
               return 0;
            int prev = nums[0], i = 0;
            for (int j=i+1; i < nums.size()-1; ) {
                while (j < nums.size() && prev == nums[j]) {
                    j++;
                }
                if (j == nums.size())
                   break;
                prev = nums[j];
                nums[++i] = nums[j];
                j++;
            }
            return i+1;
    }

方法3,进一步简化代码,方法2中的prev考虑去除。

    int removeDuplicates(vector<int>& nums) {
        if (nums.empty())
            return 0;
        int i=0, j = i+1;
        while(j < nums.size()) {
           if (nums[i] == nums[j]) j++;
           else if (j == nums.size()) break;
           else nums[++i] = nums[j++];
        }
        return i+1;
    }

TODO: 最优c++代码 https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/11782/Share-my-clean-C%2B%2B-code

2. python版本

    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        i, j = 0, 1
        while j < len(nums):
            if nums[i] == nums[j]:
                j = j+1
            elif j == len(nums):
                break
            else:
                i = i+1
                nums[i] = nums[j]
                j = j+1
        return i+1

相关文章

网友评论

      本文标题:LeetCode 26. Remove Duplicates f

      本文链接:https://www.haomeiwen.com/subject/cbhsphtx.html