Java code implementation deletes a repeating element inside an ordered array __java

Source: Internet
Author: User

Relaxed so many days, finally put the blog back to pick up, after the day to maintain 3 more, refueling refueling.

The algorithm for this implementation is to delete the repeating elements in an ordered array

Train of thought: An array is ordered, so the algorithm is relatively simple to implement, because only compare the array adjacent to two digits, there are two situations

1: If there is no element in the array or there is only one element, then there is no need to compare, directly return the length of the array;

2: If the length of the array is greater than one, then you need to compare the adjacent two elements of the array. If it is equal then the pointer of the latter element moves back one bit, and then the pointer of the previous element is then moved backward, assigning the number indicated by the current second element pointer to the position indicated by the previous element pointer. Then the latter element pointer continues to add one. If the adjacent elements are unequal, the immediate preceding element pointer is superimposed with the latter element, and then the latter element pointer continues to add one.

The code is as follows:

public class Solution {
public int removeduplicates (int[] A) {
int i=0;
int j=1;
if (a.length==0| | A.length==1) {
return a.length;
}
while (I<a.length&&j<a.length) {
if (A[i]==a[j]) {
j + +;
}else{
A[++i]=a[j++];
}

}
return i+1;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.