C# 寫 LeetCode easy #27 Remove Element

2七、 Remove Element數組

  Given an array nums and a value val, remove all instances of that value in-place and return the new length.this

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.spa

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

Example 1:blog

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.

Example 2:索引

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

Your function should return length = , with the first five elements of  containing , , , , 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.

代碼:5nums0130
static void Main(string[] args)
{
    int[] nums = { 0, 1, 3, 3, 4, 3, 5 };
    Console.WriteLine(RemoveElement(nums,3));
    Console.ReadKey();
}

private static int RemoveElement(int[] nums, int val)
{
    int index = 0;
    for(int i=0;i<nums.Length;i++)
    {
        if (nums[i] != val)
        {
            nums[index] = nums[i];
            index++;
        } 
    }
    return index;
}            

解析:element

輸入:數組和某個元素rem

輸出:刪除後的數組元素個數input

代碼思想string

  用index記錄在值不相同時的索引,循環遍歷元素,若不相同將記錄索引處的值用當前值覆蓋,最後增長索引計數。

時間複雜度:O(n)

相關文章
相關標籤/搜索