每日演算法——leetcode系列
問題 Remove Element
Difficulty: Easy
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn`t matter what you leave beyond the new length.
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
}
};
翻譯
刪除元素
難度係數:簡單
給定一個陣列和一個值, 刪陣列中所跟這個值相同的元素並返回新的長度
可以改變元素的順序, 陣列不用考慮返回的新的長度後面的元素。
思路
這題只管得到正確的長度,遍歷陣列,如果元素等於指定的值長度就不增加就好
另外可以考慮用distance
程式碼
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int len = 0;
for (size_t i = 0; i < nums.size(); ++i){
if (nums[i] != val){
nums[len++] = nums[i];
}
}
return len;
}
};