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.
Solution1: two pointers 不考虑顺序
两个指针left和right,left指第一个element,right指最后一个element。
如果A[right] == elem,直接跳过。
然后如果A[left] == elem,将right所指的element复制给left,left++, right--。
两个指针left和right,left指第一个element,right指最后一个element。
如果A[right] == elem,直接跳过。
然后如果A[left] == elem,将right所指的element复制给left,left++, right--。
Run time complexity is O(n), constant space.
public class Solution { public int removeElement(int[] A, int elem) { if(A == null || A.length == 0) return 0; int l = 0, r = A.length - 1; while(l <= r) { if(A[r] == elem) { r--; continue; } if(A[l] == elem) { A[l] = A[r]; l++; r--; }else { l++; } } return r + 1; } }Solution2:仍然保持顺序
public class Solution { public int removeElement(int[] A, int elem) { if(A == null || A.length == 0) return 0; int p1 = 0, p2 = 0; while(p2 < A.length) { if(A[p2] == elem) { p2++; }else { A[p1] = A[p2]; p1++; p2++; } } return p1; } }
No comments:
Post a Comment