LeetCode Online Judge 题目C# 练习 - 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.
1 public static int RemoveElemtn(int[] A, int n, int elem) 2 { 3 for (int i = 0; i < n; i++) 4 { 5 if (A[i] == elem) 6 { 7 A[i] = A[n - 1]; 8 n--; 9 i--; 10 } 11 } 12 return n; 13 }
代码分析:
这个应该是考审题,或者面试官之给你题目第一句话,让你去问他的前设条件,他再给你题目的第二句话。
应为题目说order可以变,new length以外的不管。那么就碰到 A[i] == elem, 把当前最后一个元素复制到A[i], 然后 长度 n--, i--(因为重后面复制上来的值可能会等于elem的,要重新审查一次这个 A[i]。