Remove Element

来源:互联网 发布:日本旅游花费 知乎 编辑:程序博客网 时间:2024/05/16 04:38

题目描述:
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 in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.

  • 这道题目要求从一个包含多个数字的数组中,移除和目标值相同的,返回不相同的个数,这个问题如果没有任何限制条件会很简单,但题目要求不能使用额外的空间,所以不能通过申请其他数组的形式来解答该题。
  • 对于这类问题,最直接的方法就是移动,即把不需要的元素移到数组的后边,或者把需要的元素移到数组的前边(这一种相对简单,只需利用一个变量即可),最后返回一个需要数据的个数即可。
    *相对来说,前移的会简单,因为在从头遍历的时候,假设遍历到第i个元素和目标值相同,则第i+1个前移的时候会把第i个覆盖,因为知道第i个不符合,所以可直接进行覆盖。
  • 而如果把不符的后移,移动的时候需判断后边的一个是否满足约束,逻辑比之前的复杂。

需要的元素迁移:

public class Solution {    public int removeElement(int[] nums, int val) {        int len=0;        Arrays.sort(nums);        for(int i=0;i<nums.length;i++){            if(nums[i]!=val){                nums[len]=nums[i];                len++;            }        }        return len;    }}
0 0
原创粉丝点击