leetcode解题方案--027--Remove Element

来源:互联网 发布:linux 批量删除进程 编辑:程序博客网 时间:2024/05/20 16:32

题目

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 by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

分析

从前向后遍历数组,如果遇到相同的就将后面的元素复制过来。因此需要维持一个尾指针。

class Solution {    public int removeElement(int[] nums, int val) {        int end = nums.length-1;        int ans = 0;        for (int i = 0; i<=end;i++) {           if (nums[i] != val) {               ans++;           } else {               while (end>i&&nums[end]==val) {                   end--;               }               if (nums[end]!=val) {                   nums[i] = nums[end];                   end--;                   ans++;               }           }        }        return ans;    }}