Question 26, delete duplicate entries sorted array

I, entitled 1

Here Insert Picture Description

Second, the idea

It is the double pointer, pointing to a traverse position, pointing to a location not repeat the last number.

Third, the code

public class T0026 {

    public static void main(String[] args) {

        int[] nums= { 1, 1, 2, 2, 3, 4, 5, 5 };
        System.out.println( removeDuplicates( nums ) );

        for ( int i : nums )
            System.out.println( i );

    }

    public static int removeDuplicates(int[] nums) {

        if ( nums.length < 2 )
            return nums.length;

        int len = 1;

        for ( int i = 1; i < nums.length; i++ ){
            if ( nums[i-1] != nums[i] )
                nums[len++] = nums[i];
        }

        return len;

    }
}


  1. Source: stay button (LeetCode)
    link: https: //leetcode-cn.com/problems/remove-duplicates-from-sorted-array
    copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source. ↩︎

Published 48 original articles · won praise 1 · views 845

Guess you like

Origin blog.csdn.net/weixin_45980031/article/details/104249390