Given an array and a value, remove all occurrences of that value in place and return the new length.
The order of elements can be changed, and the elements after the new length don't matter.
Given an array [0,4,4,0,0,2,4,4]
, value=4
return 4
and front four elements of the array is [0,0,0,2]
可能是写的不够好,left最后对应的数可能是要删除的数,也可能不是,要检查一下。这种方法会比第二种方法快一点,因为是通过两个指针交换实现的。
第二种方法代码比较清晰,不需要最后检查,但是会稍微慢一点。
public class Solution { /** *@param A: A list of integers *@param elem: An integer *@return: The new length after remove */ public int removeElement(int[] A, int elem) { // write your code here if(A == null) return 0; if(A.length == 0) return 0; int left = 0; int right = A.length - 1; while(true){ while(left < right && A[left] != elem) left++; while(left < right && A[right] == elem) right--; if(left == right) break; swap(A, left, right); } if(A[left] == elem) return left; else return left + 1; } public void swap(int[] A, int i, int j){ int temp = A[i]; A[i] = A[j]; A[j] = temp; return; }}
public class Solution { /** *@param A: A list of integers *@param elem: An integer *@return: The new length after remove */ public int removeElement(int[] A, int elem) { // write your code here if(A == null || A.length == 0) return 0; int tail = 0; for(int i = 0; i < A.length; i++){ if(A[i] != elem){ A[tail++] = A[i]; } } return tail; }}