RemoveDuplicatesFromSortedArrayI:
问题描述:给定一个有序数组,去掉其中重复的元素。并返回新数组的长度。不能使用新的空间。
[1,1,2,3] -> [1,2,3] 3
算法思路:用一个数字记录新数组的最后一个元素的位置
1 public class RemoveDuplicatesFromSortedArray { 2 3 public int removeDuplicates(int[] nums) 4 { 5 if(nums.length == 0) 6 { 7 return 0; 8 } 9 int key = nums[0]; 10 int count = 0;//记录新数组最后一个元素的位置,即新数组长度 11 for(int i = 0; i < nums.length; i ++) 12 { 13 if(nums[i]!=key) 14 { 15 nums[count++] = key; 16 key = nums[i]; 17 } 18 } 19 nums[count++] = key; 20 return count; 21 } 22 }
与之类似的就是移除数组里某个元素。
1 public int removeElement(int[] nums, int val) { 2 if(nums.length == 0) 3 { 4 return 0; 5 } 6 int count = 0; 7 for(int i = 0; i < nums.length; i ++) 8 { 9 if(nums[i]!=val) 10 { 11 nums[count++] = nums[i]; 12 } 13 } 14 return count; 15 }
RemoveDuplicatesFromSortedArrayII:
问题描述:可以重复一次。
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
算法分析:这种题目,要巧妙利用数组的下标,和上一题解法相似,只不过,循环里的判断条件变了。
//[1,1,1,2,2,3] -> [1,1,2,2,3] 5 允许重复一次
public class RemoveDuplicatesfromSortedArrayII
{
public int removeDuplicates(int[] nums)
{
if(nums.length == 0 || nums.length == 1)
{
return nums.length;
}
int count = 1, temp = nums[1];
for(int i = 2; i < nums.length; i ++)
{
if(nums[i] != nums[i - 2])
{
nums[count++] = temp;
temp = nums[i];
}
}
nums[count++] = temp;
return count;
}
}