Leetcode: 26- delete duplicates in sorted array

26. Remove 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 do it under the condition of using 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:

为什么返回数值是整数,但输出的答案是数组呢?

请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。

你可以想象内部操作如下:

// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
    
    
    print(nums[i]);
}

Ideas

不能从题目中获取有用的信息 == 不能看懂题!!!

题目中说,删除排序数组中的重复项,这样的重复项有一个非常重要的特点:
那就是所有的重复项都会连在一起,看了官方给出的代码思路,自己了理清手码了出来!

Code

class Solution {
    
    
    public int removeDuplicates(int[] nums) {
    
    	

		//排除特殊情况
        if(nums.length == 0){
    
    
            return 0;
        }
		//为数组的第一个元素赋值,因为第一个元素是不可能重复的
        int count = 0;
        nums[count] = nums[0];
		
		//从第二个开始遍历
        for(int j=1; j<nums.length; j++){
    
     
        //没有重复
            if(nums[count] !=nums[j]){
    
    
                count++;
                nums[count] = nums[j];
            }
        }
		//这边注意count++,数组下标总是比长度小1
        return count+1;

    }
}

test

Insert picture description here

Guess you like

Origin blog.csdn.net/JAYU_37/article/details/107273346