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.
维护一个指针从前往后扫, 如果碰到与给定的target相同的就把当前的和num[len]调换继续扫描, 并把len - 1 复杂度是O(n)
public class Solution { public int removeElement(int[] nums, int val) { if(nums == null || nums.length == 0) { return 0; } int len = nums.length - 1; for (int i = 0; i <= len; i++) { if (nums[i] == val) { nums[i] = nums[len]; i--; len--; } } return len + 1; } }
没有评论:
发表评论