您的位置:首页 > 编程语言 > Java开发

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));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode java 算法