Master also has to brush force button 07

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 space, you must modify the input array and use O(1) extra space.
Example 1:
given array nums = [1,1,2],
the function should return a new length of 2, and the original array nums first two elements is modified 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],

New function should return length 5, and the original array nums first five elements is modified 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]); }

public static class Solution1 {
    
    
	public 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;
	}
}

Guess you like

Origin blog.csdn.net/qq_45864370/article/details/108743474