Problem Description
Delete duplicate items in a 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.
Example 1:
Given the array nums = [1,1,2], the function should return the new length 2, and the first two elements of the original array nums are modified to 1, 2.
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 are modified to 0 , 1, 2, 3, 4.
solution
The question is very obvious. Use a double pointer to compare the previous element with each element after it, because this is a sorted array. When there are different values, assign the latter. Subscript the number of the outer loop, and finally output the value of the outer loop.
Code
//双指针方法
int[] nums = {
0,0,1,1,1,2,2,3,3,4};
if(nums==null || nums.length == 1){
System.out.println(nums.length);
}
int i = 0;
int j = 1;
while(j<nums.length){
if(nums[i]==nums[j]){
j++;
}else{
i++;
nums[i]=nums[j];
j++;
}
}
System.out.println(i+1);
to sum up
This question is limited because it can only be operated in situ, otherwise a hashMap can be introduced for storage. In that case, the judgment is very simple.