首页 > 代码库 > 【leetcode】Remove Element

【leetcode】Remove Element

题目:

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.

解析:已知一个数组和某个值elem,移除数组的所有等于elem的值(即替换到数组尾端),并且返回新的数组长度。解法是用两个变量p1和p2从数组的头和尾分别向彼此的方向移动,如果A[p1] == elem且A[p2] != elem 则将p1和p2上的元素位置调换,直到p1==p2。

Java AC代码:

public class Solution {
	
	public int removeElement(int[] A, int elem) {
		if (A == null || A.length == 0) {
			return 0;
		}
		int p1 = 0, p2 = A.length - 1;
		while (p1 < p2) {
			while (A[p2] == elem && p1 < p2) {
				p2--;
			}
			while (A[p1] != elem && p1 < p2) {
				p1++;
			}
			if (p1 < p2) {
				int temp = A[p2];
				A[p2] = A[p1];
				A[p1] = temp;
			}
		}
		return A[p1] == elem ? p1 : p1 + 1;
	}
}


【leetcode】Remove Element