LeetCode_27---Remove Element
2015-06-11 21:58
573 查看
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.
翻译:
Code:
package mengdexinTest;
import java.util.Arrays;
public class LeetCode27 {
//340ms --- 两头走
public static int removeElement(int[] nums, int val) {
int i = 0, j = nums.length - 1;
System.out.println("1j:" + j);
while (i <= j) {
while (i < nums.length && nums[i] != val) {
i++;
}
while (j >= 0 && nums[j] == val) {
j--;
}
System.out.println("2j:" + j);
if (i < j) {
nums[i] = nums[j];
--j;
++i;
}
System.out.println("3j:" + j);
}
System.out.println("4j:" + j);
return j+1;
}
// 316msA --- 一头走
public static int removeElement1(int[] nums, int val) {
int i = 0, j = 0, n = nums.length;
while (j < n) {
if (nums[j] != val) {
nums[i] = nums[j];
++i;
}
++j;
}
return i;
}
//332msA --- 一前一後
public static int removeElement2(int[] nums, int val) {
int i = 0, j = 0, n = nums.length;
while (j < n) {
if(nums[j]!= val){
nums[i++] = nums[j];
}
++j;
}
return i;
}
public static void main(String[] args) {
int[] a = { 1, 2, 2, 2, 3, 3, 6, 9 };
int[] b = { 1, 2, 3 };
int[] c = { 2, 2, 2 };
int[] d = { 4,5 };
int e = 2;
System.out.println("第二种:" + removeElement(a, e));
System.out.println("第二种:" + Arrays.toString(a));
}
}
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
翻译:
Code:
package mengdexinTest;
import java.util.Arrays;
public class LeetCode27 {
//340ms --- 两头走
public static int removeElement(int[] nums, int val) {
int i = 0, j = nums.length - 1;
System.out.println("1j:" + j);
while (i <= j) {
while (i < nums.length && nums[i] != val) {
i++;
}
while (j >= 0 && nums[j] == val) {
j--;
}
System.out.println("2j:" + j);
if (i < j) {
nums[i] = nums[j];
--j;
++i;
}
System.out.println("3j:" + j);
}
System.out.println("4j:" + j);
return j+1;
}
// 316msA --- 一头走
public static int removeElement1(int[] nums, int val) {
int i = 0, j = 0, n = nums.length;
while (j < n) {
if (nums[j] != val) {
nums[i] = nums[j];
++i;
}
++j;
}
return i;
}
//332msA --- 一前一後
public static int removeElement2(int[] nums, int val) {
int i = 0, j = 0, n = nums.length;
while (j < n) {
if(nums[j]!= val){
nums[i++] = nums[j];
}
++j;
}
return i;
}
public static void main(String[] args) {
int[] a = { 1, 2, 2, 2, 3, 3, 6, 9 };
int[] b = { 1, 2, 3 };
int[] c = { 2, 2, 2 };
int[] d = { 4,5 };
int e = 2;
System.out.println("第二种:" + removeElement(a, e));
System.out.println("第二种:" + Arrays.toString(a));
}
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统