LeetCode-80: 删除排序数组中的重复项 II
題目描述:
給定一個排序數組,你需要在原地刪除重復出現的元素,使得每個元素最多出現兩次,返回移除后數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組并在使用 O(1) 額外空間的條件下完成。
示例?1:
給定 nums = [1,1,1,2,2,3],
函數應返回新長度 length = 5, 并且原數組的前五個元素被修改為 1, 1, 2, 2, 3 。
你不需要考慮數組中超出新長度后面的元素。
示例?2:
給定 nums = [0,0,1,1,1,1,2,3,3],
函數應返回新長度 length = 7, 并且原數組的前五個元素被修改為?0, 0, 1, 1, 2, 3, 3 。
你不需要考慮數組中超出新長度后面的元素。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
?
C++:
class Solution {
public:
? ? int removeDuplicates(vector<int>& nums) {
? ? ? ? if (nums.size() <= 2) {
? ? ? ? ? ? return nums.size();
? ? ? ? }
? ? ? ??
? ? ? ? int index=0;
? ? ? ? for(int i=2;i<nums.size();++i){
? ? ? ? ? ? if(nums[index] != nums[i]){
? ? ? ? ? ? ? ? nums[index+2]=nums[i];
? ? ? ? ? ? ? ? ++index;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ??
? ? ? ? return index+2;
? ? }
};
?
?
C:
int removeDuplicates(int* nums, int numsSize){
? ? ? ? if (numsSize <= 2) {
? ? ? ? ? ? return numsSize;
? ? ? ? }
? ? ? ??
? ? ? ? int index=0;
? ? ? ? for(int i=2;i<numsSize;++i){
? ? ? ? ? ? if(nums[index] != nums[i]){
? ? ? ? ? ? ? ? nums[index+2]=nums[i];
? ? ? ? ? ? ? ? ++index;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ??
? ? ? ? return index+2;
}
?
總結
以上是生活随笔為你收集整理的LeetCode-80: 删除排序数组中的重复项 II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode-26: 删除排序数组中
- 下一篇: ubuntu中安装kDevelop