Topic:
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 are you leave beyond the new length.
Translation:
Given an array and a value, remove all instances of this value in place, and return the new array length.
The order of the elements can be changed. and the array in the new length of the section, you can not go to the tube it.
Analysis:
My practice is to swap all elements that are not given values to the front position of the array. This is done with some optimizations, that is, instead of replacing the given value to the back, replace the non-specified value with the previous one. I created a pointer (array subscript) that represents the current array position that can be written as a new value, and at the end of the loop it is also the length of the new array.
Code:
publicclass Solution { publicintremoveElement(intint val) { int nextEmpty=0; for(int i=0;i<nums.length;i++){ if(nums[i]!=val){ nums[nextEmpty]=nums[i]; nextEmpty++; } } return nextEmpty; }}
Leet Code OJ 27. Remove Element [Difficulty:easy]