Given a sorted array, remove the duplicates in place such that each element appear onlyOnceAnd return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A =[1,1,2]
,
Your function shocould return length =2
, And a is now[1,2]
Problem:
Remove the repeated values in the given array and return the length of the array after deduplication. Note that the problem requires that another array cannot be defined, so the results are saved in the input array.
Ideas:
Compare the records from the first to the second. If the values are not the same, they are saved to A. If the values are equal, they are moved back until the results are saved every time they are found. Finally, the length of the index record of the New Result array is used.
For example, array [,]
First, compare and define result = 1. A [result ++] is used to save the result array.
1! = 2 so a [Result] is a [1], so a [1] = 2, and another result ++ is followed by result = 2;
2 = 2 so do not save, continue backward loop comparison.
2! = 3 so a [Result] is a [2], so a [2] = 3, and result = 3 after result ++'
.......
The loop ends until the end. result is the new array length, and a is the deduplicated array.
public class Solution { public int removeDuplicates(int[] A) { int length = A.length; int result = 1; if(length<=1) return length; else{ for(int i=0;i<length-1;i++){ if(A[i]!=A[i+1]){ A[result++]=A[i+1]; } } } return result; }}
Leetcode -- remove duplicates from sorted Array