算法题丨Remove Element

简介: 描述Given an array and a value, remove all instances of that value in-place and return the new length.

描述

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.

示例

Given nums = [3,2,2,3], val = 3, Your function should return length = 2, 
with the first two elements of nums being 2.

算法分析

难度:低
分析:给定数组和指定一个目标值,从数组中移除所有跟目标值相等的元素,返回最终元素的长度,注意不要另外分配内存空间。
思路:题目很简单,直接遍历数组元素,判断当前元素是否跟目标值相等,如果不相等,证明当前元素应该留在数组中,有效数组长度自增1,否则为无效元素,因为只需返回有效数组长度,所以不用删除元素,跳过此循环即可。

代码示例(C#)

public int RemoveElement(int[] nums, int val)
{
    int i = 0;
    for (int j = 0; j < nums.Length; j++)
    {
        //如果不相等,有效长度自增1
        if (nums[j] != val)
        {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
}               

复杂度

  • 时间复杂度O (n).
  • 空间复杂度O (1).

附录

img_8f0a90f3cbaa0e044fb8bf7b13c4317b.jpe

文章作者:原子蛋
文章出处:https://www.cnblogs.com/lizzie-xhu/
个人网站:https://www.lancel0t.cn/
个人博客:https://blog.lancel0t.cn/
微信公众号:原子蛋Live+
扫一扫左侧的二维码(或者长按识别二维码),关注本人微信公共号,获取更多资源。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

目录
相关文章
|
Java
Remove Element
Remove Element删掉指定的元素,并用后面的元素顶替空出来的位置;Remove ElementGiven an array and a value, remove all instances of that value in place and return the new length.
705 0
LeetCode - 27. Remove Element
27. Remove Element Problem's Link  ---------------------------------------------------------------------------- Mean:  移除数组中的指定元素.
865 0
|
人工智能 C++ Python
leetcode 27 Remove Element
 Remove Element Total Accepted: 60351 Total Submissions: 187833 My Submissions                       Given an array and a valu...
828 0
|
Java C++
LeetCode之Remove Element
LeetCode之Remove Element
122 0
|
Python 人工智能
LeetCode 27 Remove Element
题目描述: Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. 题目翻译:给定一个数组A和一个值elem,删除所有的elem,并返回新的数组长度。
775 0
|
9月前
|
存储 算法 对象存储
【C++11算法】minmax和minmax_element
【C++11算法】minmax和minmax_element
214 0

热门文章

最新文章