Remove Duplicates from Sorted Array
Harvest:
1. "Delete" elements in an array
2. Array output
Topic:
Given A sorted array, remove The duplicates in place such, all element appear only Onc e and return the new length.
Do the allocate extra space for another array, and you must does this on place with constant memory.
For example,
Given input array nums = [1,1,2]
,
Your function should return length = 2
, with the first of the elements of nums being and 1
2
re Spectively. It doesn ' t matter what are you leave beyond the new length.
The title means: Return the number of the new array is not repeated, and before the output of these numbers (but not to delete the duplicate number, the duplicate number assignment is placed in the back), if the number of output is correct, but the number of output array is incorrect, will also error
Ideas:
My idea: I don't know how to delete an array
Leetcode: Moves the next non-repeating value forward, and the duplicate value is assigned to the last value, so that the first length of the output is not duplicated.
Code
1 classMyClass2 {3 Public:4 intRemoveduplicate (vector<int>nums)5 {6 intj =0, n =0;7n =nums.size ();8 for(size_t i =1; I < n; i++)9 {Ten if(Nums[i-1] ==Nums[i]) One { AJ + +; - } - Else theNUMS[I-J] = nums[i];//highlights of the area - } - returnN-J; -}
My Test code:
1 //Remove duplicates from Sorted Array.cpp: Defines the entry point of the console application. 2 //3 4#include"stdafx.h"5#include"iostream"6#include"Vector"7 8 using namespacestd;9 Ten classMyClass One { A Public: - intRemoveduplicate (vector<int>nums) - { the intj =0, n =0; -n =nums.size (); - for(size_t i =1; I < n; i++) - { + if(Nums[i-1] ==Nums[i]) - { +J + +; A } at Else -NUMS[I-J] =Nums[i]; - } - returnN-J; - } - }; in - to int_tmain (intARGC, _tchar*argv[]) + { -vector<int> nums = {1,2,2,3,4,5,5 }; the MyClass solution; *vector<int>m; $ intn =0;Panax Notoginsengn =solution.removeduplicate (nums); -cout << N <<Endl; the //test output array with + /* A For (size_t i = 0; i < m.size (); i++) the { + cout << m[i] << ""; - } $ cout << Endl;*/ $System"Pause"); - return 0; -}
2016.6.17--remove Duplicates from Sorted Array