27 Remove Element
2015-08-08 18:37
190 查看
题目链接:https://leetcode.com/problems/remove-element/
题目:
解题思路:
1. i 指针从前向后扫描,遇到值为 val 的位置停下;j 指针从后向前扫描,遇到值为非 val 的位置停下。
2. 交换 i 和 j 位置的元素值。(可以不用交换直接覆盖)
3. 如果 i == j,则判断 i 当前位置的元素值是否为 val,若不为val,说明 i 扫描到了数组的末尾,且 i
之前(包括i)的元素都是有效元素,则长度为 i + 1。
4. 其余情况,i 值即为数组长度。
注意:
有几种特别的输入样例:
[3, 3] 3
[3, 3] 1
需要特别考虑!
要比
节省时间得多!
交换元素的方法:
后来想到了可以用 j 位置的元素直接覆盖 i 位置的元素
题目:
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.
解题思路:
1. i 指针从前向后扫描,遇到值为 val 的位置停下;j 指针从后向前扫描,遇到值为非 val 的位置停下。
2. 交换 i 和 j 位置的元素值。(可以不用交换直接覆盖)
3. 如果 i == j,则判断 i 当前位置的元素值是否为 val,若不为val,说明 i 扫描到了数组的末尾,且 i
之前(包括i)的元素都是有效元素,则长度为 i + 1。
4. 其余情况,i 值即为数组长度。
注意:
有几种特别的输入样例:
[3, 3] 3
[3, 3] 1
需要特别考虑!
nums[i] = nums[j]; j --;
要比
nums[i] = nums[j --];
节省时间得多!
交换元素的方法:
public class Solution { public int removeElement(int[] nums, int val) { if(nums == null || nums.length == 0) return 0; int len = nums.length; if(len == 1) { if(nums[0] == val) return 0; else return 1; } int i = 0; int j = len - 1; while(i < j) { while(nums[i] != val && i < j) i ++; while(nums[j] == val && i < j) j --; if(nums[i] == val && nums[j] != val) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } if(nums[i] != val && i == j) { i ++; break; } } return i; } }
112 / 112 test cases passed. Status: Accepted Runtime: 300 ms
后来想到了可以用 j 位置的元素直接覆盖 i 位置的元素
public class Solution {
public int removeElement(int[] nums, int val) {
if(nums == null || nums.length == 0)
return 0;
int len = nums.length;
if(len == 1) {
if(nums[0] == val)
return 0;
else
return 1;
}
int i = 0;
int j = len - 1;
while(i < j) {
while(nums[i] != val && i < j)
i ++;
while(nums[j] == val && i < j)
j --;
if(nums[i] == val && nums[j] != val) {
nums[i] = nums[j]; j --;
}
if(nums[i] != val && i == j) {
i ++;
break;
}
}
return i;
}
}
112 / 112 test cases passed. Status: Accepted Runtime: 268 ms
相关文章推荐
- 代码从记事本拷贝到 source insight 工程出现中文乱码解决办法
- ABP(现代ASP.NET样板开发框架)系列之22、ABP展现层——导航栏设置
- flowplayer视频播放插件
- Android 网络:基于TCP协议通信,多线程,实现简单的C/S聊天室
- HDU 2191
- Leetcode48 Rotate Image
- HDU2102 A计划 (基础BFS)
- 转:“智齿”到底该不该拔?
- JAVA中CLASS.FORNAME的含义
- python发送电子邮件
- 关于synchronized具备原子性的问题
- python文本文件,生成指定的文件格式
- 清除浮动的几种方式
- [leedcode 235] Lowest Common Ancestor of a Binary Search Tree
- JS - 鼠标经过边框旋转
- ajax提交下载文件
- springMVC的json交互
- iOS APP图标长按抖动效果的实现(CAAnimation)
- Java中普通代码块,构造代码块,静态代码块区别及代码示例
- 【CF 459D】 Pashmak and Parmida's problem