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 = [,,,], val = ,

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

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

Example 2:

Given nums = [,,,,,,,], val = ,

Your function should return length = , with the first five elements of nums containing , , , , and .

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 = ; i < len; i++) {
print(nums[i]);
}

我的解题思路:遍历整个数组,逐个检查每个值是否与要求移除的值相同,如果相同,则将后面的值依次向前移动一个位置,并从当前位置重新开始检查。

遍历结束之后再检查最后一个位置的数是不是要求移除的值,如果是 返回值减1;

看代码:

public class Solution {
public int RemoveElement(int[] nums, int val) {
if(nums.Length == )
return ;
int i,j,length=nums.Length;
for(i = ; i < length; i++){
if(nums[i] == val){
for(j = i; j < length - ; j++){
nums[j] = nums[j+];
}
length--;
i--;//i递减1之后,从当前位置重新检查
}
}
if(length != && nums[length-] == val)//检查最后一个数字是不是需要移除的值
length--;
return length;
}
}

最新文章

  1. 字符串hash算法
  2. 《ASP.NET1200例》ListView控件之修改,删除与添加
  3. win7如何设置某个软件不弹出用户账户控制
  4. SAS软件的使用和统计学分析的初步介绍
  5. 简单的刷票系统(突破IP限制进行投票) (转)
  6. 运维之Linux基础知识(三)
  7. 201521123075 《Java程序设计》第11周学习总结
  8. linux清屏命令(clear,reset)
  9. load vs. initialize
  10. Android系统修改硬件设备访问权限
  11. redis 系列9 对象类型(字符串,哈希,列表,集合,有序集合)与数据结构关系
  12. JAVA8给我带了什么——lambda表达
  13. ChromeDriver与Chrome版本对应关系
  14. Jupyter Notebook 入门
  15. window server 2012 更改密钥 更改系统序列号
  16. firefox插件之 vimperator 的使用
  17. POJ3903Stock Exchange&amp;&amp;POJ1631Bridging signals最长上升子序列 &amp;&amp;POJ1887Testing the CATCHER(最长下降子序列)(LIS模版题)
  18. poj21516
  19. Python变量、字符练习1
  20. 0050 MyBatis关联映射--一对多关系

热门文章

  1. java虚拟机规范(se8)——class文件格式(三)
  2. vue实现全选反选--简单使用
  3. C#编程--第二天
  4. linux 软件管理--yum工具及源码包
  5. test命令-linux shell 脚本
  6. Python随笔记录之一
  7. React 滚动事件
  8. 学习java设计模式有用吗?懂这六个原则,编程更轻松
  9. Springboot项目静态资源配置
  10. 工程师技术(四):配置SMB文件夹共享、多用户Samba挂载、普通NFS共享的实现、安全NFS共享的实现