27. Remove Element(Java)

Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Example: Given input array nums = [3,2,2,3], val = 3 Your function should return length = 2, with the first two elements of nums being 2.

本题比较简单,就是首先遍历该数组,如果数组元素的遍历时遇到与给定值相同的值,则将该元素删除,也就是用j+1的值覆蓋j的值,注意当删除该元素之后,记得将遍历数组的指针向前移动一个(因为此时该指针指向的值还没有遍历,所以要将指针向前移动一个,即就是代码中的i–)

public class Solution {
    public int removeElement(int[] nums, int val)
	{
		if(nums == null)
			return 0;
		
		int len = nums.length;
		for(int i = 0; i < len; i++)
		{
			if(nums[i] == val)
			{
				for(int j = i; j < len - 1; j++)
				{
					nums[j] = nums[j + 1];
				}
				len--;
				i--;//注意将指针向前移动
			}
		}
		return len;
	}
}

点赞