美文网首页
Oct-17-2018

Oct-17-2018

作者: 雨生_ | 来源:发表于2018-10-17 21:53 被阅读21次

争取每周做五个LeedCode题,定期更新,难度由简到难

Title: Remove Element

Description:

Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

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

Example:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Difficulty:

Easy

Implement Programming Language:

C#

Answer:

这个题跟之前的比较像,思路比较简单,就是把需要的放到前面,然后返回长度就行。破坏数据无所谓,需求说的。

public static 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];
                    n--;
                }
                else
                {
                    i++;
                }
            }
            return n;
        }
Github

相关文章

  • Oct-17-2018

    争取每周做五个LeedCode题,定期更新,难度由简到难 Title: Remove Element Descri...

网友评论

      本文标题:Oct-17-2018

      本文链接:https://www.haomeiwen.com/subject/bzrdzftx.html