Description
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.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
分析
題目要求對一數組刪除指定的元素后形成的新數組。
注意:本題要求只能在原數組的基礎上修改,不準定義其他數組。因此修改完原數組后,還應當返回新數組的元素的個數。
思路一
首先定義一個變量k來表示數組中與給定元素相異的個數,初始值設為0,然后從前往后逐個掃描數組,若發現與制定元素不同,則k+1,并且將該元素填入數組的第k位上,直到掃描完全部元素。掃描完成后k表示數組中與指定元素相依的元素個數,返回k即可。思路二
使用兩個指針分別指向數組A的首和尾,假設i指向首,j指向尾,指定元素為elem。如果A[i]等于elem則需要替換掉該元素,我們可以從后邊找一個與elem不同的元素填入該處,如果A[i]不等于elem則i加1,若A[j]等于指定元素則j減1,這樣當i大于j時我們就將所有不同元素放到數組的前邊了,此時i為不同元素的個數。
C語言代碼
//思路一
int removeElement(int A[], int n, int elem)
{
int i=0,j=0;
for(i=0;i<n;i++)
{
if(A[i]!=elem)
A[j++]=A[i];
}
return j;
}
//思路二
int removeElement(int A[], int n, int elem)
{
int i=0,j=n-1,k=0;
while(i<=j)
{
if(A[i]==elem&&A[j]!=elem)
{
A[i]=A[j];
A[j]=elem;
}
if(A[i]!=elem)
i++;
if(A[j]==elem)
j--;
}
return j+1;
//結束循環的條件時i>j,由于j每次只移動一位,因此跳出循環時j即滿足j+1=i。而i只有在A[i]!=elem的時候增加,即i時數組中與elem相異的數的個數。
}
int main()
{
int arr[]={3,2,2,3};
int elem=2;
removeElement(arr, 4, 3);
return 0;
}
參考文獻
[1] https://leetcode.com/problems/remove-element/#/description
[2] https://hk029.gitbooks.io/leetbook/