26. Delete duplicates in the sorted array (implemented in java) --LeetCode

table of Contents

topic:

Solution 1: Double pointer

Solution 2: Double pointer


topic:

https://leetcode-cn.com/problems/remove-duplicates-from-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.

Do not use extra array of space, you have to modify the input array place and completed under the conditions of use 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.
for (int i = 0; i <len; i++) {     print(nums[i]); }

 

Solution 1: Double pointer

/**
 * 思路:
 * 双指针
 * 一个记录不重复元素的位置index,一个不断前移
 * 只要nums[n]!=nums[n-1]的就将这个元素放到index
 */
    public int removeDuplicates(int[] nums) {
        int index=1;
        for (int i=1;i<nums.length;i++){
            if (nums[i]!=nums[i-1]){
                nums[index++]=nums[i];
            }
        }
        return index;
    }

Time complexity: On

Space complexity: O1

Solution 2: Double pointer

/**
 * 思路:
 * 双指针
 * 一个指向不重复元素位置,一个不断前移
 * 比较两个下标的元素值,不等就进行换位
 */  
    public int removeDuplicates(int[] nums) {
        int index=0;
        for (int i=1;i<nums.length;i++){
            if (nums[i]!=nums[index]){
                nums[++index]=nums[i];
            }
        }
        return index+1;
    }

Time complexity: On

Space complexity: O1

 

Guess you like

Origin blog.csdn.net/qq_38783664/article/details/110386783