26.Remove Duplicates from Sorted Array Easy 1591 3410 Favorite Share Given a sorted array nums , remove the duplicatesin-placesuch that each element appear only once and return the new length. Do not allocate extra space for another array,
Given a sorted array nums, remove the duplicates in-place such that each element appear only once 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.
Example 1:
Given nums = [1,1,2], Your function should return length = , with the first two elements of being and respectively. It doesn‘t matter what you leave beyond the returned length.2nums12
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = , with the first five elements of being modified to , , , , and respectively. It doesn‘t matter what values are set beyond the returned length.
Main Problem is to correctly understand the problem ,when I first saw this function I see int is the return type.
I only think it‘s need return the number of sum,but actually it also need to move vector variable
The most unimaginable thing is this problem only see first-N variable.You needn‘t see the last of array,You
even needn‘t delete them from your vector.Unimaginable
But it also reflect that I‘m not familiar with the method to delete from STL vector.
Special Remind,In myfunction main function fo not watch(不配套) with the solution part.Main use to see the vector‘s constitute
5nums01234
#include <iostream> #include<vector> #include<iostream> #include<string> #include<stdio.h> #include<string.h> #include<iomanip> #include<vector> #include<list> #include<queue> #include<algorithm> #include<stack> #include<map> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: int removeDuplicates(vector<int>& nums) { const int n=nums.size(); //special case if(n<=1) return n; //int res=0,keep=nums[0]; int ans=0,j; for(int i=0;i<n;) { nums[ans++]=nums[i]; j=i+1; while(j<n&&nums[j-1]==nums[j]) j++; i=j; } return ans; } }; //class Solution { //public: // vector<int>& removeDuplicates(vector<int>& nums) { // const int n = nums.size(); // //if (n <= 1) return n; // int ans = 0; // int i = 0; // while (i < n) { // nums[ans++] = nums[i]; // int j = i + 1; // while (j < n && nums[j] == nums[j - 1]) ++j; // i = j; // } // return nums; // } //}; int main() { ListNode a(1); ListNode b(2); ListNode c(3); ListNode d(4); ListNode e(5); Solution s; a.next=&b; b.next=&c; c.next=&d; d.next=&e; ListNode *head=&a; // while(head) // { // cout<<head->val<<endl; // head=head->next; // } //ListNode* res=NULL; vector<int> nums; vector<int> res; nums.push_back(1); nums.push_back(1); nums.push_back(2); res=s.removeDuplicates(nums); //ShowVec(res); //cout<<res<<endl; // res=s.reverseKGroup(head, k); for(auto v:res) { cout<<v<<endl; } return 0; }