问题描述:(切记!!!给出的数组必须有序)
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
问题解决思路:
有两种解决办法
1,利用数组下标和中间变量解决
2,利用快慢指针解决
具体内容请看代码注释
代码实现:
package Algorithm;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
public class Example2 {
//利用数组下标和临时变量处理数组问题
public static int GainArreylength1(int[] array){
if (array == null || array.length == 0){
return 0;
}
if (array.length == 1){
return 1;
}
else{
int temp = array[0];//一般情况将临时变量设置为数组的第一个元素
int len = 1;
for (int i = 1; i < array.length; i++){
if (temp == array[i]){//如果后面的元素和temp相等,那就一直往后找
continue;
}
else {//如果遇到不相等的,立即更新temp,并给计数器len+1
temp = array[i];
array[len] = array[i];//这是为了最后返回去掉重复数字后的数组
len ++;
}
}
return len;
}
}
//利用快慢指针来处理去除重复问题(其中有一个问题,快慢指针的方法在无时无刻的改变
//数组array的值,所以如果要返回去重后的数组,不太容易)
public static int GainArreylength2(int[] array ){
if (array.length == 0){
System.out.print("数组为空");
}
int i = 0;//i为慢指针
for (int j = 1; j < array.length; j++ ){//j为快指针
if (array[j] != array[i] ){//当快慢指针不相等时
i++;//移动慢指针
array[i] = array[j];//将快指针所指向的数组值赋给慢指针所指向的数组
}
}
return i+1;
}
public static void main(String[] args) {
int[] num = {0,0,1,1,3,3,5,5,6};
System.out.print(GainArreylength1(num));
}
}
Java解决有序数组去重:LeetCode算法题解析
本文探讨了如何在LeetCode中解决有序数组去重的问题,强调了数组必须有序这一前提。通过两种方法进行解答,包括使用数组下标和中间变量,以及利用快慢指针。尽管在不考虑时间复杂度和空间复杂度的情况下问题简单,但题目要求O(n)时间和O(1)空间,因此双指针成为常见解法。
1259

被折叠的 条评论
为什么被折叠?



