26. 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 by modifying the input array in-place with O(1) extra memory.

Example:

Givennums= [1,1,2],Your function should return length = 2, with the first two elements ofnumsbeing 1 and 2 respectively.It doesn't matter what you leave beyond the new length.

分析:

一开始将题目理解错误,此题只是检测相邻两个元素是不是重复,而不是说最后的结果不能有重复数字,例如输入为 [1,1,2,3,1],输出结果应为[1,2,3,1],而不是[1,2,3]。理解这一点后,着手解题过程:

我的正向思路是:遇到重复的数字,将后面的内容以此向前提一个位置,这样结果中就会忽略了重复的元素,实现方法是将当前内容复制给前一个 (a[i -1] = a[i])。如下图所示:



在这里我们有一个记录repeat的变量,初始化为0

----在index = 1 时遇到了第一次repeat,repeat++,此时repeat = 1

----继续index = 2时,不重复了,将a[2] 复制到 a[1]

----在index = 3 时遇到了第二次repeat,repeat++,此时repeat = 2

----继续index = 4时,不重复了,将a[4] 复制到 a[2]

       继续index = 5时,不重复了,将a[5] 复制到 a[3]

       继续index = 6时,不重复了,将a[6] 复制到 a[4]

----在index = 7 时遇到了第三次repeat,repeat++,此时repeat = 3

----继续index = 8时,不重复了,将a[8] 复制到 a[5]

整个动态过程,如下图所示:



通过上面的分析,我们可以得到,在不重复情况下,下标移动的变量为a[i - repeat] = a[i],重复情况下,repeat++。代码如下:

class Solution {public: int removeDuplicates(vector& nums) {

        int repeat = 0;


        for(int i = 1; i < nums.size(); i++)

        {

            if(nums[i] == nums[i-1]) repeat++;

            else nums[i - repeat] = nums[i];             

        }

        return nums.size() - repeat;

    }

};

效率图如下,继续继续!



附第27. Remove Element 非常类似

Given an array and a value, remove all instances of that value in-place 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.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:

Givennums= [3,2,2,3],val= 3,Your function should return length = 2, with the first two elements ofnumsbeing 2.

代码只有一点改动,如下:

class Solution {public: int removeElement(vector& nums, int val) {

        int repeat = 0;

        for(int i = 0; i < nums.size(); i++)

        {

            if(nums[i] == val) repeat++;

            else nums[i - repeat] = nums[i];           

        }

        return nums.size() - repeat;

    }

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容