27. Remove Element

来源:互联网 发布:mac 查看所有进程 编辑:程序博客网 时间:2024/05/23 10:20

原题

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.

题目分析

要求移除指定元素,空间复杂度为O(1)。

代码实现

public int RemoveElement(int[] nums, int val)    {        int i=0; //指向不等于元素val        for(int j=0; j<nums.Length;j++)        {            while(j<nums.Length&&nums[j]==val)                j++;            if(i<j && j<nums.Length)              nums[i]= nums[j];            if(j<nums.Length)              i++;        }        return i;    }

leetcode-solution库

leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp

2 0
原创粉丝点击