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.
**Example1: **
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.
**Example2: **
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.python
題目要求不使用額外的空間,移除全部數值等於val的元素,返回新數組的長度,因而想到使用替換的方法。
將數組中數值等於val的元素與數組最後一個元素互換,再將最後一個元素刪除。這樣就完成了一個刪除數值等於val元素的操做。數組
//聲明一個int類型的向量vec vector<int> vec; //聲明一個int類型,初始大小爲10的向量vec vector<int> vec(10); //聲明一個int類型,初始大小爲10,且元素都爲0的向量vec vector<int> vec(10, 0); //聲明一個int類型的向量vec,並用向量vec1初始化vec vector<int> vec(vec1); // 利用數組arr的前五個元素初始化向量vec int arr[5] = {0, 1, 2, 3, 4}; vector<int> vec(arr, arr + 5);
//下標訪問,不會進行越界檢查 vec[0] //at訪問,會檢查越界,若是出界會拋出out of range 異常 vec.at(0) //訪問第一個元素 vec.front() //訪問最後一個元素 vec.back()
//在int類型的向量vec的末尾添加一個int元素1 vec.push_back(1); //刪除vec的最後一個元素 vec.pop_back(); //在vec的pos位置插入元素element vec.insert(pos, element); //將向量vec中pos1位置與pos2位置的元素互換(swap能夠用來釋放內存) vec.swap(pos1, pos2); //刪除向量vec中pos位置的元素 vec.erase(pos); //刪除向量vec中pos1位置到pos2位置的元素 vec.erase(pos1, pos2); //清空向量vec vec.clear();
在容器vector中,其內存佔用的空間是隻增不減的,好比說首先分配了10,000個字節,而後erase掉後面9,999個,則雖然有效元素只有一個,可是內存佔用仍爲10,000個。全部內存空間在vector析構時回收。通常,咱們都會經過vector中成員函數clear進行一些清除操做,但它清除的是全部的元素,使vector的大小減小至0,卻不能減少vector佔用的內存。函數
//向量vec的大小,它告訴你容器裏有多少元素。 vec.size() //向量vec的分配容量,能夠大於size。它告訴你容器在已經分配的內存中總共能夠容納多少元素。 vec.capacity() //釋放int類型的向量vec的內存 vector<int>().swap(vec); //下降vec的容量,使其與size匹配(可用於刪除元素後,節省向量的空間) vec.shrink_to_fit() //爲容器預留空間,但在空間內不真正建立元素對象,因此在沒有添加新的對象以前,不能引用容器內的元素。 //使用push_back添加新元素 vec.reserve(10); for(int i = 0; i < 10; i++) vec.push_back(1); //改變容器的大小,同時建立對象。 //resize有兩個參數,第一個是容器大小,第二個參數時新加入容器的元素。 //調用這個函數以後,可使用[]添加新元素。 vec.resize(10); vec[0] = 0; //將第一個元素賦值爲0
class Solution { public: int removeElement(vector<int>& nums, int val) { for(int i=0;i<nums.size();i++){ if(nums[i] == val){ nums[i] = nums.back(); nums.pop_back(); //對交換來的數組最後一個元素也進行檢查,防止數組最後一個元素數值也等於val i--; } } return nums.size(); } };
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ while val in nums: nums.pop(nums.index(val)) return len(nums)