[Java] 80. Remove duplicates from Sorted Array II Java

Source: Internet
Author: User

Topic:

Follow up for "Remove duplicates":
What if duplicates is allowed at the most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3] ,

Your function should return length =, with the first 5 five elements of nums being 1 , 1 2 2 ,, and 3 . It doesn ' t matter what are you leave beyond the new length.

test instructions and analysis : An ascending array is given, and the duplicate elements are removed, and each element can only appear at most two times after deletion .

Code Listing 1: record How many consecutive numbers are currently, if less than or equal to 2, write directly, if greater than 2, write only the first two digits. The number of the last faces of an array needs to be judged separately

classSolution { Public intRemoveDuplicates (int[] nums) {        if(nums.length==0)return0; intres = 0; intCount = 1;//record consecutive number of numbers         for(inti=0;i<nums.length;i++){            if(I>0 && nums[i]==nums[i-1]) {count++; if(COUNT&GT;2)Continue;//More than two times skip directly            }            Else{//The current number is not equal to the previous number, reset to 1Count=1; } nums[res++] =Nums[i]; }        returnRes; }}

Code two: (1) If the i<2 is added directly into the array, (2) Otherwise if the current number has existed before two, then skip, otherwise add into the array

class Solution {    publicint removeduplicates (int[] nums) {        int i = 0;          for (int  n:nums)             if (I < 2 | | n > nums[i-2])                nums[i+ +] = n        ; return i;    }}

[Java] 80. Remove duplicates from Sorted Array II Java

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.