A written test every day-leetCode 26. Delete duplicates in the sorted array

A written test every day-leetCode 26. Delete duplicates in the sorted array

leetCode 26. Delete duplicates in sorted array

Given a sorted array, you need to delete the repeated elements in place, so that each element only appears once, and return the new length of the removed array.

Don't use extra array space, you must modify the input array in situ and complete with O(1) extra space.

Example 1:

Given array nums = [1,1,2],

The function should return the new length 2, and the first two elements of the original array nums have been modified to 1, 2.

You don't need to consider the elements in the array beyond the new length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

The function should return the new length of 5, and the first five elements of the original array nums have been modified to 0, 1, 2, 3, 4.

You don't need to consider the elements in the array beyond the new length.

Description:

Why is the returned value an integer, but the output answer is an array?

Please note that the input array is passed by "reference", which means that modifying the input array in the function is visible to the caller.

You can imagine the internal operation as follows:

// nums is passed by "reference". In other words, do not make any copy of the actual parameters
int len ​​= removeDuplicates(nums);

// Modifying the input array in the function is visible to the caller.
// According to the length returned by your function, it will print out all the elements in the array within that length range.
for (int i = 0; i <len; i++) { print(nums[i]); }

Method: double pointer method

code show as below:

package cn.lbl.face.leetCode;

/*
给定数组 nums = [1,1,2],

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。

你不需要考虑数组中超出新长度后面的元素。

 */
public class 删除排序数组中的重复项2 {
    
    
    public static void main(String[] args) {
    
    
//        System.out.println( removeDuplicates(new int[]{1,1,2}));
        System.out.println( removeDuplicates(new int[]{
    
    0,0,1,1,1,2,2,3,3,4}));
//        System.out.println( removeDuplicates(new int[]{0,0,1,1,1,2,2,3,3,4}));
    }

    //双指针法
    //快慢指针 i(慢)  j(快)
    public static int removeDuplicates(int[] nums) {
    
    
        int i=0;
        for (int j = 1; j <nums.length ; j++) {
    
    
            if (nums[i] != nums[j]) {
    
    
                i++;
                nums[i]=nums[j];
            }
        }
        return i+1;
    }
}

Complexity analysis

时间复杂度:O(n),假设数组的长度是 n,那么 i 和j 分别最多遍历 n 步。

空间复杂度:O(1)。

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_37924905/article/details/108718920