Algorithm-delete duplicates in sorted array (double pointer method)

LeetCode address

Question:
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 place and use O(1) extra space.

Example 1:

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

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

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

Example 2:

给定 nums = [0,0,1,1,1,2,2,3,3,4],

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

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

Realization idea:
Two people by default, one p, one q, q stand in front of p,

  • If the p position and the q position value are not the same, then both of them will step forward (p and q are not next to each other, so you need to assign the q position value to the p+1 position, and then both will take a step forward; p and q is next to each other, no need to re-assign, just use both to step forward)
  • If it is the same, then p does not move and q one step forward;
  • Until p comes to an end;

achieve:

class Solution {
    
    
	public int removeDuplicates(int[] nums) {
    
    
		int p = 0;
		int q = 1;
		while (q < nums.length) {
    
    
			if (nums[p] != nums[q]) {
    
    
				if ((p + 1) < q) {
    
    
					nums[p + 1] = nums[q];
				}
				p++;
			}
			q++;
		}
		return p + 1;
	}
}

Only this record, if there is a problem with the code or there is a better way to implement it, please leave a message, thank you

Guess you like

Origin blog.csdn.net/nongminkouhao/article/details/107957454