LeetCode_Remove Element

来源:互联网 发布:神速百度快速排名优化 编辑:程序博客网 时间:2024/05/21 05:21

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.

分析:题目给出一个数组和一个值val,要求删除这个数组中所有等于val的元素,返回一个新的长度,比如原数组中共有5个元素:{1,2,3,3,4},不仅返回新长度4,并且将原数组的前4个元素改为:1,2,3,4(第5个元素无所谓,前4个元素顺序无所谓)。

java解题:

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


0 0
原创粉丝点击