leetcode:Remove Element 【Java】

一、问题描述

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.

二、问题分析

添加一个下标指针即可。

三、算法代码

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


你可能感兴趣的:(leetcode)