您的当前位置:首页正文

Oct-17-2018

来源:华拓网

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

Title:

Description:

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;
        }