27. Remove Element

来源:互联网 发布:js回车事件 编辑:程序博客网 时间:2024/06/16 03:41

题目描述

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.

去除所有例子中的值,返回一个新的长度,不要分配额外的空间给另外的数组,你必须做这个在连续的内存,要求值能够被改变。

思路

第一种解法:

删除那个出现的那个值,返回长度。循环,找到就删,但是长度减一,最后面的找不了了,找到打标记最后删,需要开辟一个数组。因此想了一个办法,找到就删除,遍历的时候 从第一个重新开始。

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int i;        for(i = 0; i < nums.size(); i++)        {            if(nums[i] == val)            {                 nums.erase(nums.begin()+i);                 i = -1;            }        }        return nums.size();    }};
第二种解法:

j是不相等的数组的长度,不相等的话,前面的就被替换。

class Solution{ public:             int removeElement(int A[],int n,int elem)    {                                   int i = 0;                  int j = 0;                  for(i = 0;i < n;i++)        {                                               if(A[i] !=  elem)               {                                   A[j++]=A[i];//不相等的话就赋给j                 }                           }                           return  j;              } };
第三种解法:

如果与val相等,那么将最后一个值赋给当前的i,然后长度减一,从i这边再次判断,不相等,数组下标往前移动。

public int removeElement(int[] nums, int val) {    int i = 0;    int n = nums.length;    while (i < n) {        if (nums[i] == val) {            nums[i] = nums[n - 1];            // reduce array size by one            n--;        } else {            i++;        }    }    return n;}
原创粉丝点击