leetcode数组专项习题:删除元素

版权声明:本文为博主原创,未经允许请不要转载哦 https://blog.csdn.net/weixin_43277507/article/details/88178695

16.删除元素
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.
题设要求:给定一个数组和一个值,删除该值的所有实例并返回新的长度。可以更改元素的顺序。
分析:如果不考虑额外空间的开销,比较简单的方法是建立一个list,将原始数组中不等于指定值的元素放入list。但本题还可以从i=0开始往后遍历数组,跳过指定值,没跳过一次数组长度减一。这样既可以在原地改变数组,同时也得到了新的长度。
代码:

public class Solution{
    public static void main(String[] args) 
    {
    	Solution sl = new Solution();
        int[] A= {4,5};
        int elem = 4;
        int len =sl.removeElement(A, elem);
        System.out.println(len);
     }
    
    public int removeElement(int[] nums, int val) {
        int n=nums.length;
        int i=0;
        while(i<n){
            if(nums[i]==val){
                n--;
                nums[i]=nums[n];
            } else{
                i++;
            }
        }
        return n;
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_43277507/article/details/88178695