Remove Duplicates from Sorted Array

Source: Internet
Author: User

Package Cn.edu.xidian.sselab.array;

/**
*
* @author Zhiyong Wang
* Title:remove duplicates from Sorted Array
* Content:
* Given a sorted array, remove the duplicates in place such, all element appear only once and return the new length.
* Do not 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 1 and 2 respectively. It doesn ' t matter what are you leave beyond the new length.
*/
public class Removeduplicatesfromsortedarray {

This problem is almost the same as removeelement, because it is an array that has been sequenced, and the comparison condition is changed to the adjacent two numbers.
Also is the logarithm of the number of the statistic double, the number of the same number of each number forward
But when compared to pay attention to the problem, do not cross the border, here is particularly important, nums inside the number of less than 2 times, do not do any processing, only more than 1 will be compared
public int removeduplicates (int[] nums) {
int length = Nums.length;
int count = 0;
if (length>1) {
for (int i=1;i<length;i++) {
if (nums[i-1] = = Nums[i]) {
count++;
}else{
Nums[i-count] = nums[i];
}
}
}
return length-count;
}
}

?

Remove duplicates from Sorted Array

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.