Java removes repeating elements from a sorted array _java

Source: Internet
Author: User

Topic description

Given an ordered array, remove the repeating element from the array, leaving only a duplicate element and returning the new array length.

Requirements:
Do not assign extra space to the array, you must use the constant memory size for the in-situ operation.

For example:
To the array of a=[1,1,2], your function calls must return the length length=2, and a now becomes [1,2].

Input

An array of sorts, such as [1,1,2].

Output

Returns the new length of the array, such as length=2.

Fast and Fast pointer method

Sets the fast pointer to traverse the array, and the slow pointer points to the next digit of the element that does not repeat.

public static int removeduplicates (int[] nums)
{
  if (Nums.length < 1) return
    nums.length;
  int slow = 1;
  for (int fast = 1; fast < Nums.length fast++) {
    if (nums[fast)!= nums[slow-1]) {
      nums[slow++] = Nums[fast ];
    }
  }
  return slow;
}

Animation Demo:

Extended

Removes a repeating element from a sorted array and retains the specified number of digits.

public static int removeduplicatesn (int[] nums, int repeatn)
{
 if (nums.length <= repeatn)
  return Nums.length;
 int index = REPEATN;
 for (int i = Repeatn i < nums.length i++) {
  if (nums[i)!= Nums[index-repeatn]) {
   nums[index++] = nums[i];< c8/>}
 } return
 index;

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.