我是靠谱客的博主 勤劳枕头,最近开发中收集的这篇文章主要介绍(双指针) leetcode 27. Remove Element,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Given an array nums and a value val, 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 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

------------------------------------------------------------------------------------------------------------------------------------

这个题如果没有说明"in place" 这个条件的话,也许会更容易,但是,这个已经说明要原地修改数组,也就是要空间复杂度为O(1),于是,我们可以用双指针。我们可以用一个慢指针和快指针,快指针用来从头到尾依次遍历这个原数组,然后用当遍历到不是val的数时,这个数组对应的慢指针指向的索引的数更新,慢指针加一。

C++代码:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int k = 0;
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] != val){
                nums[k] = nums[i];
                k++;
            }
        }
        return k;
    }
};

 

转载于:https://www.cnblogs.com/Weixu-Liu/p/10785163.html

最后

以上就是勤劳枕头为你收集整理的(双指针) leetcode 27. Remove Element的全部内容,希望文章能够帮你解决(双指针) leetcode 27. Remove Element所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部