27. Remove Element-Easy-Array
Problem
Given an array nums and a value val, remove all instances of that value in-placeand 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 1:
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 =5
, with the first five elements ofnums
containing0
,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.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this
// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
Tag
two-pointers
Relative background knowledge
“凡是數組的題目,大部分都是利用雙指針去解決問題。”
雙指針,顧名思義,就是利用兩個指針去遍歷數組,一般來說,遍歷數組采用的是單指針(index)去遍歷,兩個指針一般是在有序數組中使用,一個放首,一個放尾,同時向中間遍歷,直到兩個指針相交,完成遍歷,時間復雜度也是O(n)。
用法
一般會有兩個指針front
,tail
。分別指向開始和結束位置。
front = 0;
tail = A.length()-1
一般循環結束條件采用的是判斷兩指針是否相遇
while(fron < tail)
{
……
}
對於in place交換的問題,循環結束條件一般就是其中一個指針遍歷完成。
使用範圍
一般雙指針在有序數組中使用的特別多。(部分情況下,未排序數組也有應用) 一般用來解決下列問題(陸續補充中):
1. 兩數求和
一般這種問題是問,尋找兩個數的和為一個特定的值(比如後面的N SUM問題),這時候,如果數組有序,我們采用兩個指針,分別從前和後往中間遍歷,front移動和增大,tail移動和減小,通過特定的判斷,可以求出特定的和。時間復雜度為O(n),如果用雙重循環則要O(n^2)。
2. in place交換
數組的in place(就地)交換一般得用雙指針,不然數組中添加或刪除一個元素,需要移動大量元素。
這時候,一般是一個指針遍歷,一個指針去找可以用來交換的元素。
Solution
It depends on whether val is rare in the array.
1. If val is not rare:
class Solution { public int removeElement(int[] nums, int val) { int newLength = 0 ; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) { nums[newLength++] = nums[i]; } } return newLength; } }
2. If val is rare:
The pointer starts from the tail to the head.
Complexity
time complexity:O(n)
space complexity:O(1)
27. Remove Element-Easy-Array