Given an array nums and a value val, 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. 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 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. 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]); } 複製代碼
給定數組號和值val,刪除該值的全部實例並返回新的長度。
不要爲另外一個數組分配額外的空間,您必須使用O(1)額外內存修改輸入數組。
元素的順序能夠改變。在新的長度以外留下什麼並不重要。
示例1:
給定nums = [3,2,2,3], val = 3,
函數應該返回length = 2, nums的前兩個元素爲2。
在返回長度以外留下什麼並不重要。
示例2:
給定nums = [0,1,2,2,3,0,4,2], val = 2,
函數應該返回length = 5, nums的前五個元素包含0、一、三、0和4。
注意,這五個元素的順序能夠是任意的。
在返回長度以外設置什麼值並不重要。
澄清:
爲何返回的值是整數而您的答案是數組?
注意,輸入數組是經過引用傳入的,這意味着調用者也知道對輸入數組的修改。
你能夠這樣想:
// nums是經過引用傳入的。(即。,無須複印)
int len = removeElement(nums, val);
//函數中對nums的任何修改都會被調用者知道。
//使用函數返回的長度,它輸出第一個len元素。
for (int i = 0;i<len;i++){
print (num[i]);
}數組
本題思路很簡單,該題和第26題很類似,這邊是移除了指定的相同數字,並且本題對順序沒有要求,那麼咱們能夠經過遍歷,把相同的數據放到後面,返回非指定數字的數量就能夠了bash
按照咱們的思路來編輯,代碼以下函數
int index = 0;
int len = nums.length;
for (int i = 0; i < len - index; i++) {
if (nums[i] != val) {
continue;
}
int temp = len - 1 - index;
nums[i] = nums[i] ^ nums[temp];
nums[temp] = nums[temp] ^ nums[i];
nums[i] = nums[temp] ^ nums[i];
i--;
index++;
}
return len - index;
複製代碼
時間複雜度: 該方案用了循環,循環層數爲1;因此O(f(n))=O(n),即T(n)=O(n)優化
空間複雜度: 該方案沒有使用額外的空間,因此空間複雜度是O(1);ui
本題的大體解法如上所訴,本題本人沒法想到優化的方式,只是利用了位運算來簡化了換位的方式。this