26题删除数组中的重复元素
80题删除数组中的重复元素,使得数组中值相同的元素最多出现两次
27题删除数组中的指定元素
283题删除数组中的0
这几道题相对简单,实质是一样的,采用 Two Pointers 可实现多题一解,归纳为一个系列的题。
题目这里就不在描述,可点击下面的题目链接查看原题
26. Remove Duplicates from Sorted Array
Two Pointers:一个指针跟踪原始数组中的当前元素,另一个指针跟踪唯一元素
Time complexity :
O
(
n
)
O(n)
O(n)
Space complexity :
O
(
1
)
O(1)
O(1)
/*
Two Pointers
一个指针跟踪原始数组中的当前元素,另一个指针跟踪唯一元素
*/
//Time complexity : O(n); Space complexity : O(1)
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;
int index = 0;
for(int i = 1; i < nums.length; i++){//若遇到重复元素,即nums[i]==nums[index],i++直接进入下一个循环即可
if(nums[i] != nums[index]){
index++;
nums[index] = nums[i];
}
}
return index + 1;
}
}
80. Remove Duplicates from Sorted Array II
Two Pointers:一个指针跟踪原始数组中的当前元素,另一个指针跟踪出现不超过两次的元素
Time complexity :
O
(
n
)
O(n)
O(n)
Space complexity :
O
(
1
)
O(1)
O(1)
/*
Two Pointers
一个指针跟踪原始数组中的当前元素,另一个指针跟踪出现不超过两次的元素
*/
//Time complexity : O(n); Space complexity : O(1)
class Solution {
public int removeDuplicates(int[] nums){
if(nums.length <= 1) return nums.length;
int index = 1;
for(int i = 2; i < nums.length; i++){
if(nums[i] != nums[index-1]){
index++;
nums[index] = nums[i];
}
}
return index+1;
}
}
27. Remove Element
Two Pointers:一个指针跟踪原始数组中的当前元素,另一个指针跟踪值不为val的元素
Time complexity :
O
(
n
)
O(n)
O(n)
Space complexity :
O
(
1
)
O(1)
O(1)
/*
Two Pointers
一个指针跟踪原始数组中的当前元素,另一个指针跟踪值不为val的元素
*/
//Time complexity : O(n); Space complexity : O(1)
class Solution {
public int removeElement(int[] nums, int val) {
if(nums.length == 0) return 0;
int index = 0;
for(int i = 0; i < nums.length; i++){//若元素值为val,i++直接进入下一个循环即可
if(nums[i] != val){
nums[index] = nums[i];
index++;
}
}
return length;
}
}
283. Move Zeroes
Two Pointers:一个指针跟踪原始数组中的当前元素,另一个指针跟踪非0元素
此题要求"move all 0’s to the end of it(nums[])",所以除了非0元素置于数组头部,还要在将元素0置于数组尾部。可采用swap交换两元素或人为末尾补0这两种方法。
Time complexity :
O
(
n
)
O(n)
O(n)
Space complexity :
O
(
1
)
O(1)
O(1)
/*
Two Pointers
一个指针跟踪原始数组中的当前元素,另一个指针跟踪非0元素
*/
//Time complexity : O(n); Space complexity : O(1)
class Solution {
public void moveZeroes(int[] nums) {
if(nums == null || nums.length == 0) return;
int index = 0;
for(int i = 0; i < nums.length; i++){//若元素值为0,i++直接进入下一个循环即可
if(nums[i] != 0){
nums[index] = nums[i];
index++;
}
}
//人为补0
for(int i = index; i < nums.length; i++){
nums[i] = 0;
}
}
}
/*
Two Pointers
一个指针跟踪原始数组中的当前元素,另一个指针跟踪非0元素
*/
//Time complexity : O(n); Space complexity : O(1)
class Solution {
public void moveZeroes(int[] nums) {
if(nums == null || nums.length == 0) return;
int index = 0;
for(int i = 0; i < nums.length; i++){//若元素值为0,i++直接进入下一个循环即可
if(nums[i] != 0){
int temp = nums[i];
nums[i] = nums[index];
nums[index] = temp;
index++;
}
}
}
}