"Leetcode" Remove duplicates from Sorted Array problem Solving report
tags (space delimited): Leetcode
[Leetcode]
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Total accepted:129010 Total submissions:384622 difficulty:easy
Question
Given a sorted array, remove the duplicates in place such it each
Element appear only once and return the new length.
Do not allocate extra space for another array, you must does this in
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 1 and 2 respectively. It doesn ' t matter what are you leave
Beyond the new length.
Ways
This question is a double pointer.
Basic over AC.
It is important to note that the count initial value is 1, and the meaning of this is that the contents of the array are not empty if they are returned directly at the bottom.
The first commit is as follows and is optimized later.
Public class solution { Public int RemoveDuplicates(int[] nums) {if(nums.length<=1)returnNums.length;intHead=0;intnext=1;intCount=1; while(Next < Nums.length) { while(Nums[head] = = Nums[next]) {next++;if(next>=nums.length)returnCount } nums[head+1]=nums[next]; head++; next++; count++; }returnCount }}
Ac:1ms
The following is the official answer to Leetcode. I didn't know it at first, but to see it, I said, just don't wait to change the next element of the head pointer to the element that the tail pointer points to. If equal, the tail hands continue to move backwards.
publicintremoveDuplicates(int[] nums) { if0return0; int0; for (int1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return1;}
After referencing this I have optimized my code:
Public class solution { Public int RemoveDuplicates(int[] nums) {if(nums.length<=1)returnNums.length;intHead=0;intnext=1; while(Next < Nums.length) {if(Nums[head] = = Nums[next]) {next++;Continue; } nums[head+1]=nums[next]; head++; next++; }returnHead+1; }}
Ac:2ms
It's slowing down?
Date
May 8, 2016
"Leetcode" Remove duplicates from Sorted Array problem Solving report