27. Remove Element - 移除元素-Easy
Description:
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 in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2, with the first two elements of nums being 2.
思路分析:
1.最终要求的是输出除给定值以外的其他数组中的值,所写方法需要返回的是这些值的总个数,即输入[3,2,2,3]==>输出:2,并且数组的新状态为[2,2,3,3];
2.最近在复习排序算法,所以这个问题很亲切,其中也一种排序的影子,只不过是把特定的值而不是最大值放到最后,问题还有一个约束:只能用常数级的额外空间,即O(n)=1,所以不能通过额外的数组来记录给定值以外的值完成;
3.因此,排序里面每一次循环里怎么把局部最大值移动到局部的最后,这里也可沿用,只不过,这里问题有其特殊性:值一旦已经确定了,不需要后续的一轮比较来确定(排序的时候最大值需要这样来确定),一旦遍历到就可以直接当做‘最大值’来移动到最左边,而且最大值只有一个,但特定值可以同时出现。
C#代码:
1 public class Solution { 2 public int RemoveElement(int[] nums, int val) { 3 int j=nums.Length-1,len= nums.Length,i=0; 4 while(j>=i){ 5 if(nums[j]==val){ 6 len--; 7 j--; 8 continue; 9 } 10 if(nums[i]==val){ 11 int temp = nums[i]; 12 nums[i] = nums[j]; 13 nums[j] = temp; 14 len--; 15 j--; 16 }else{ 17 i++; 18 } 19 if(i==j){ 20 break; 21 } 22 } 23 return len; 24 } 25 }
或者:
public class Solution { public int RemoveElement(int[] nums, int val) { int len= nums.Length; for(int i=0;i<nums.Length;i++){ if(i==len)break; if(nums[i]==val){ if(nums[len-1]==val){ len--; i--; continue; } int temp = nums[i]; nums[i] = nums[len-1]; nums[len-1] = temp; len--; } } return len; } }
posted on 2017-03-12 23:44 codingHeart 阅读(532) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?