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.
思路:
两层循环,注意删除元素时指针要回溯,此方法的时间复杂度为O(n^2)
1 public class Solution { 2 public int removeElement(int[] A, int elem) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int len = A.length; 6 for(int i = 0; i < len;){ 7 if(A[i] == elem){ 8 for(int j = i + 1; j < len; j++){ 9 A[j - 1] = A[j]; 10 } 11 len --; 12 continue; 13 } 14 i++; 15 } 16 return len; 17 } 18 }
双指针,时间复杂度为O(n)
1 public int removeElement(int[] A, int elem) { 2 int len = A.length; 3 int cur = 0; 4 for(int i = 0; i < len; i ++){ 5 if(A[i] == elem) 6 continue; 7 8 A[cur] = A[i]; 9 cur ++; 10 } 11 return cur; 12 }