Topic:
Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.
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
Respectivel Y. It doesn ' t matter what are you leave beyond the new length.
Test instructions
Given a sorted array, deleting duplicate elements in the array causes each element in the array to appear only once, returning the new length of the array.
Do not allocate space for the new array, you must use constant space.
Like what:
Given the input array nums = [1,1,2]
,
The function you write needs to return a length of 2, and the two elements 1
2。
数组中的超过这个长度的元素无关紧要。
in the array are and
Algorithm Analysis:
With double pointers
* Front and back two pointers, front hands fixed, after pointer to search
* Until the pointer points to a different element than the previous pointer, then the second different element is counted, i++;
* The position of the pointer after the previous pointer is reset to the present
* Repeat the above process, to be able to count the total number of different elements, and the original array of the first I element is that I each other different elements
AC Code:
/** * Front and back two pointers, the front hands fixed, after the pointer to search * until the pointer points to a different element than the previous pointer, then the second different elements, i++; * Before the pointer resets to the current position of the pointer * Repeat the above process, to be able to count the total number of different elements, and the original array of the first I element is that I each other different elements * * public class Solution {public int RemoveDuplicates (int[] nums) {if (nums.length==0) return 0;int startindex = 0;int endindex = 0;int i=0; while (Endindex<nums.length) {while (endindex<nums.length) { if (nums[startindex]==nums[ Endindex]) endindex++; Else {break ; } } nums[i]= nums[startindex];startindex=endindex;i++; } return i; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Remove Duplicates from Sorted Array