LeetCode Day2 陣列 雙指標
阿新 • • 發佈:2020-12-22
LeetCode26. 刪除排序陣列中的重複項
解法①:c++ stl中的unique()和erase()操作
1 class Solution { 2 public: 3 int removeDuplicates(vector<int>& nums) { 4 //unique指向最後一個不重複元素的下一個元素 (key) 5 auto it_unique=unique(nums.begin(),nums.end()); 6 nums.erase(it_unique,nums.end());7 return nums.size(); 8 } 9 //[1,2,3,3,5,7,7,8,8] 10 //unique只做移動 11 };
解法②:雙指標
1 int removeDuplicates(int* nums, int numsSize){ 2 if(numsSize==0) return 0; 3 int i=1,j=1,count=1; 4 for(;i<numsSize;i++){ 5 if(nums[i]==nums[i-1]){ 6 count++;7 }else{ 8 count=1; 9 } 10 if(count<=1){ //面對不同題目時,只要修改這裡count的判斷條件即可 11 nums[j]=nums[i]; 12 j++; 13 } 14 } 15 return j; 16 }
LeetCode80. 刪除排序陣列中的重複項Ⅱ
思路:和26題解法②類似,可以套用模板。
關於模板的總結: