Leetcode: remove duplicate

有点啰嗦。
这篇都是easy题,纪念刚开始刷题的日子,一直做嵌入式,根本不了解算法。
最开始刷的一题是remove duplicates,跟这个题一样的,都是用:
manage a new index to build array。
感叹一下,以前的同学早已经在AI领域大展拳脚,我还在这里从最简单的算法开始,安慰自己开始了就好吧。

  1. Move Zeroes
    https://leetcode.com/problems/move-zeroes/description/
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int index = 0;
        for(auto num : nums)
        {
            if(num != 0)
            {
                nums[index++] = num;
            }
        }
        
        for(; index < nums.size(); index++)
        {
            nums[index] = 0;
        }
    }
};
  1. Remove Duplicates from Sorted Array
    https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int index = 0;
        for(auto num : nums)
        {
            if(index < 1 || num != nums[index-1])
            {
                nums[index] = num;
                index ++;
            }
        }
        
        return index;
    }
};
  1. Remove Duplicates from Sorted Array II
    https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int index = 0;
        
        for(auto num : nums)
        {
            if(index < 2 || num != nums[index-2])
            {
                nums[index++] = num;
            }
        }
        
        return index;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43476349/article/details/84139085
今日推荐