算法題丨Remove Element

描述

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 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.git

示例

Given nums = [3,2,2,3], val = 3, Your function should return length = 2, 
with the first two elements of nums being 2.

算法分析

難度:低
分析:給定數組和指定一個目標值,從數組中移除全部跟目標值相等的元素,返回最終元素的長度,注意不要另外分配內存空間。
思路:題目很簡單,直接遍歷數組元素,判斷當前元素是否跟目標值相等,若是不相等,證實當前元素應該留在數組中,有效數組長度自增1,不然爲無效元素,由於只需返回有效數組長度,因此不用刪除元素,跳過此循環便可。github

代碼示例(C#)

public int RemoveElement(int[] nums, int val)
{
    int i = 0;
    for (int j = 0; j < nums.Length; j++)
    {
        //若是不相等,有效長度自增1
        if (nums[j] != val)
        {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
}

複雜度

  • 時間複雜度O (n).
  • 空間複雜度O (1).

附錄

相關文章
相關標籤/搜索