27. Remove Element
2016-04-19 17:08
225 查看
iven 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 =
Your function should return length = 2, with the first two elements of nums being 2.
思路:碰到等于目标元素的甩到后面去
代码如下(已通过leetcode)
public class Solution {
public int removeElement(int[] nums, int val) {
int length=nums.length;
int i=0;
int j=length-1;
while(i<=j) {
if(nums[i]==val) {
nums[i]=nums[j];
nums[j]=val;
j--;
} else i++;
}
return j+1;
}
}
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.
思路:碰到等于目标元素的甩到后面去
代码如下(已通过leetcode)
public class Solution {
public int removeElement(int[] nums, int val) {
int length=nums.length;
int i=0;
int j=length-1;
while(i<=j) {
if(nums[i]==val) {
nums[i]=nums[j];
nums[j]=val;
j--;
} else i++;
}
return j+1;
}
}
相关文章推荐
- 一个最不可思议的MySQL死锁分析
- arm neon 优化原理
- 【转】程序包com.sun.image.codec.jpeg不存在 问题的完美解决
- Linux电源管理(4)_Power Management Interface
- OC基础----数组排序(OC)
- JAVA虚拟机之四:G1垃圾收集器
- Linux下使用popen()执行shell命令
- JS获取时间段内的工作时长
- 图像预处理第9步:存为.bmp文件
- 工程师离不开的那些电路设计工具 干货get√
- Eclipse 出现的问题总结
- java 对redis 的基本操作
- 用python进行科学统计及数据挖掘--便捷工具环境搭建
- php日记——获取当天产生的数据(比较日期)
- Android adb 命令
- NPOI使用手册
- warning C4819 解决方案 warning C4819: The file contains a character that cannot be represented in the cu
- Bundle研究
- 关于JAVA取本机ip的一些传说
- iOS根据日期、数值给model排序