Leetcode is happy to brush the fifteen days – 26. Remove duplicates from sorted array

26. Remove Duplicates from Sorted Array
Easy

< div>

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 < span style="font-size: 18px;">,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(not matching) with the solution part.Main use to see the vector's constitute
5nums01234
#include 

#include

#include

#include
<string>
#include

#include
<string.h>
#include

#include

#include

#include

#include

#include

#include

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(j1] ==nums[j])
j
++;
i
=j;
}

return ans;
}
};
//class Solution {
//public:
// vector& removeDuplicates(vector& nums) {
// const int n = nums.size();
// //if (n <= 1) return n;
// int ans = 0;
// int i = 0;
// while (i // nums[ans++] = nums[i];
// int j = i + 1;
// while (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<val<// 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=s.reverseKGroup(head, k);< /span>
for(auto v:res)
{
cout
<endl;
}
return 0;
}

26 . Remove Duplicates from Sorted Array
Easy

< /div>

26. Remove Duplicates from Sorted Array

Easy

Leave a Comment

Your email address will not be published.