Question 26:
Given a sorted array, 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 in place with constant memory.
中文解释:有一个有序的数组,里面有的数据出现了两次,其余的都只出现一次。删除这个些出现两次的数据之一,然后返回删除之后数组的长度。
For example,
Given input array nums = [1,1,2],Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
解决思路:这里我提供两种解决思路,常规套路,第一种是最直观的思路,第二种是有点技巧的思路。
1)遍历对比做标志位
这里,以Integer.MAX_VALUE 作为标志,每当碰到重复的数据,就赋值成Integer.MAX_VALUE(这里其实是有一个bug的,如果整数数组中最后的数字是Integer.MAX_VALUE 这个时候就会有bug,虽然出现的概率很小),最后做一个遍历,删除所有值为Integer.MAX_VALUE的元素。
从上面的分析可知,时间开销接近2n,时间复杂度是O(n)。空间复杂度是O(1)。
public static int removeDuplicates(int[] nums) {
int count=0;
int result = nums.length;//标识数组最后的长度
//以Integer.MAX_VALUE作为标志位
int temp = Integer.MAX_VALUE;
for(int i=0; i<nums.length-1; i++){
if( (nums[i] ^ nums[i+1])==0 ){//存在相同的数字
result--;
nums[i] = temp;
}
}
//遍历删除所有的Integer.MAX_VALUE
for(int i=0; i<nums.length; i++){
if(nums[i] == temp){
count++;
}else{
nums[i-count] = nums[i];
}
}
return result;
}
这种算法并不是什么好的算法。
2)一次遍历迭代
下面这种实现就只需要一次遍历,明显比前一种算法时间开销上节约了接近一半。
public static int removeDuplicates2(int[] nums) {
/**
//注释部分和下面的逻辑是一模一样的,只是这里用for循环,下面的用foreach迭代。
int index=0;
for(int i=0; i<nums.length-1;i++){
if(nums[i] == nums[i+1]){
}else{
nums[index++] = nums[i];
}
}
nums[index++] = nums[nums.length-1];
return index;*/
//首先做一个判断,nums的长度是否为0,如果为0直接就返回0
int i = nums.length > 0 ? 1 : 0;
for (int n : nums)//迭代每个数据,然后判断
if (n > nums[i - 1])
nums[i++] = n;
//返回数组长度
return i;
}