leetcode-27.Remove Element 移除元素
題目:
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 = 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 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]); } |
給定一個數組 nums 和一個值 val,你需要原地移除所有數值等於 val 的元素,返回移除後陣列的新長度。 不要使用額外的陣列空間,你必須在原地修改輸入陣列並在使用 O(1) 額外空間的條件下完成。 元素的順序可以改變。你不需要考慮陣列中超出新長度後面的元素。 示例 1: 給定 nums = [3,2,2,3], val = 3, 函式應該返回新的長度 2, 並且 nums 中的前兩個元素均為 2。 你不需要考慮陣列中超出新長度後面的元素。 示例 2: 給定 nums = [0,1,2,2,3,0,4,2], val = 2, 函式應該返回新的長度 說明: 為什麼返回數值是整數,但輸出的答案是陣列呢? 請注意,輸入陣列是以“引用”方式傳遞的,這意味著在函式裡修改輸入陣列對於呼叫者是可見的。 你可以想象內部操作如下: // nums 是以“引用”方式傳遞的。也就是說,不對實參作任何拷貝 int len = removeElement(nums, val); // 在函式裡修改輸入陣列對於呼叫者是可見的。 // 根據你的函式返回的長度, 它會打印出陣列中該長度範圍內的所有元素。 for (int i = 0; i < len; i++) { print(nums[i]); } |
思路:令k為 不等於 元素的給定元素的位置
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int len = nums.size();
if(len==0) return 0;
int k=0;
for(int i=0;i<len;++i)
{
if(nums[i]!=val)
nums[k++]=nums[i];
}
return k;
}
};