Problem Difficulty: Easy
Topic:
Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new L Ength.
Do not allocate extra space for another array, you must does this by modifying the input array in-place with O (1) Extra memo Ry.
Translation:
Given a sorted array, delete the duplicate elements so that each element appears only once and returns the new length.
Do not create another array to allocate additional space, only by modifying the original array, and the space complexity is O (1).
Example: [1,1,2]--[1,2] 2
Idea: A see eliminate duplicates, think of set, and then write the code as follows
1 Public int removeduplicates (int[] nums) {2 new HashSet (); 3 for (int i = 0; i < nums.length; i++) {4 s.add (Nums[i]); 5 }6 return s.size (); 7 }
But the answer says wrong??
Because the problem is special, it not only checks the final result, but also checks whether the last value of the Nums is expected (only the size of the last returned result)
Then I add an iterator to the loop to assign the value, the result is still wrong?
1 for (Iterator Iterator = s.iterator (); Iterator.hasnext ();) {2 nums[i++] = (Integer) Iterator.next (); 3 }
The order is also to tube? Well hashset disorderly , then use TreeSet bar:
1 Public intRemoveDuplicates (int[] nums) {2set<integer> s =NewTreeset<integer>();3 for(inti = 0; i < nums.length; i++) {4 S.add (Nums[i]);5 }6 inti = 0;7 for(Iterator Iterator =s.iterator (); Iterator.hasnext ();) {8nums[i++] =(Integer) Iterator.next ();9 }Ten returns.size (); One}
161/161 Test cases passed. status:accepted runtime:24 ms beats 5.31%
Since the use of set occupies extra space here, the space complexity is O (N), although the result is correct, but does not conform to the original intent, the following is the reference answer.
1 Public intRemoveDuplicates (int[] nums) {2 if(Nums.length = = 0)return0;3 inti = 0;4 for(intj = 1; J < Nums.length; J + +) {5 if(Nums[j]! =Nums[i]) {6i++;7Nums[i] =Nums[j];8 }9 }Ten returni + 1; One}
In the beginning to think about this, but after the operation found that the boundary problem is always unable to deal with, gave up,
This cleverly uses an int outside the loop to make a pointer to the original array , while the loop internally compares the pointer to the second and skips over the duplicate elements.
Period compilation Error :
1. The "=" is written in parentheses after the If "=";
2. The ToArray method of set can only use the ToArray (New Int[set.size ())) so that there will be no transformation errors, but this can only be converted to a non-basic type (integer and not NT), like an int array can only use iterators for loop assignment ;
3. Forget to write return.
Leetcode [26] (Java): Remove duplicates from Sorted array Label: array