【leetcode】刪除陣列中指定要求的重複的數字
阿新 • • 發佈:2019-01-02
1. 給定一個數組和一個值,刪除該值的所有例項,並返回新長度。 不要為另一個數組分配額外的空間,您必須使用常量記憶體來進行此操作。
元素的順序可以改變。
Given an array and a value, 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 in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
題解:
int removeElement(vector<int>& nums, int val) {
int begin=0;
int end=nums.size();
for(int i=0;i<end;++i)
{
if (nums[i]!=val)
{
nums[begin++]=nums[i];
}
}
return begin;
}
2.Remove Duplicates from Sorted Array II
從排序陣列中刪除重複陣列II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
思路:已序陣列超過2次去重,已序?
總結:兩個指標下表=下標,一個用來遍歷,一個用來將正確的元素放在正確的位置,
特別注意:
1.邊界條件的判斷,是否元素個數為0可以通過?
2.重複元素多於2個怎麼解決?
3.怎麼樣不會崩潰?
int removeDuplicates(vector<int>& nums) {
int size=0;
for(int i=0;i<nums.size();++i)
{
if(i<2)
{
size++;
}
else if(nums[i]>nums[size-2])
{
nums[size++]=nums[i];
}
}
return size;
}
再來學習一下更新穎的解法:
int removeDuplicates(vector<int>& nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}