算法题丨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.
示例
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).
附录
- 系列目录索引
- 代码实现(C#版)
- 相关算法:Move Zeroes
![]()
文章作者:原子蛋
文章出处:https://www.cnblogs.com/lizzie-xhu/
个人网站:https://www.lancel0t.cn/
个人博客:https://blog.lancel0t.cn/
微信公众号:原子蛋Live+
扫一扫左侧的二维码(或者长按识别二维码),关注本人微信公共号,获取更多资源。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
算法题丨4Sum
描述 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: The solution set must not contain duplicate quadruplets. 示例 Given array S = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ] 算法分析 难度:中分析:给定整型数组和指定一个整型目标值,从整形数组中找出4个不同的元素,使得4个元素之和等于目标值,返回结果为所有满足上述条件的元素组合。思路:思路可以参考3Sum,主要难度是由原先的找3个元素之和,变成了找4个元素之和。这种情况下,其实有点像解...
-
下一篇
算法题丨Move Zeroes
描述 Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note: 1.You must do this in-place without making a copy of the array. 2.Minimize the total number of operations. 示例 Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 算法分析 难度:低分析:给定一个数组,将所有为0的元素都移动到数组的末尾,并保持非0的元素排序保持不变。思路:首先,思考满足第1个条件很简单,就是遍历数组,判断当前元素是否为0,如果是0,将0跟当前元素互换一下,遍历完数组就可以了。但是这样处理的话,并不能保证非0元素排序不变,所以,我们放弃这种思路。 那怎...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- MySQL数据库在高并发下的优化方案
- SpringBoot2初体验,简单认识spring boot2并且搭建基础工程
- Docker容器配置,解决镜像无法拉取问题
- Docker安装Oracle12C,快速搭建Oracle学习环境
- CentOS8,CentOS7,CentOS6编译安装Redis5.0.7
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- 2048小游戏-低调大师作品
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作