Remove ElementRemove Elementhttps://leetcode.com/PRoblems/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.
算法思想:这道题跟"Merge Two Sorted Lists"是相似的。
1)定义两个pointers: i 和j。i指向第一个元素,j指向最后一个元素;定义一个元素来计算新数组的长度,初始化为原始数组的长度
2)若i指向的元素等于给定的value,那么就将i指向的这个值替换为j指向的值,然后j就往前移动一个,并且新的数组的长度需要减一个;若i指向的元素跟value不相等,那么i就继续往前移动。
3)i在j的后面的时候,跳出循环
程序清单:public class Solution { public int removeElement(int[] nums, int val) { int length = nums.length; if (length <= 0) { return length; } int i = 0; int j = length - 1; int newLen = length; do{ if (nums[i] == val) { nums[i] = nums[j]; newLen--; j--; } else { i++; } }while(i<=j); return newLen; }}