"026-remove duplicates from Sorted Array (delete duplicate elements in sorted array)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
Given a sorted array, remove the duplicates in place such, all element appear only once 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
respectively. It doesn ' t matter what are you leave beyond the new length.
Main Topic
Given a sorted array, remove the repeating elements from the array, keep only one, and return the number of new elements in the array, instead of creating a new array to hold the result. Solve this problem in constant time
Thinking of solving problems
Start processing from the second element, as the currently processed element, if the current element is the same as his previous element, delete the element, if it is different move it to the correct position, return the last array element number of people.
Code Implementation
Algorithm implementation class
Public class solution { Public int RemoveDuplicates(int[] A) {if(A.length = =0) {return 0; }intindex =0;//[0,index] Only records the only number of occurrences in an array by small to large, which is already sorted. intNext =1;//Algorithm idea: Find the number after index is larger than A[index], if found, move to a[index+1] place, //Index moves to the next position, next moves to the next position, and then the number larger than A[index] while(Next < A.length) { while(Next < A.length && A[index] = = A[next]) {//Find not equal to the most in arraynext++; }if(Next < A.length) {index++; A[index] = A[next]; next++; } }returnIndex +1; }Private void Swap(int[] A,intXintY) {intTMP = a[x]; A[X] = A[y]; A[y] = tmp; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47034985"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "026-remove duplicates from Sorted Array (delete duplicate elements in sorted array)"