Remove Element From Array
https://leetcode.com/problems/remove-duplicates-from-sorted-array/ https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
Problem 1: delete a key from an array
Problem description
Delete a key from an array
public static int deleteKey(int key, List<Integer> A) {
int writeIdx = 0;
for (int i = 0; i < A.size(); ++i) {
if (A.get(i) != key) {
A.set(writeIdx++, A.get(i));
}
}
return writeIdx;
}
Problem 2: delete duplicates from a sorted array
Problem description
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
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.
public int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
}
int writeIndex = 1;
boolean isFirstTime = true;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i-1]) {
nums[writeIndex++] = nums[i];
isFirstTime = true;
} else {
if (isFirstTime) {
nums[writeIndex++] = nums[i];
isFirstTime = false;
}
}
}
return writeIndex;
}
Follow up:
The duplicate element appear no more than m times.
public static int removeDuplicatesFromSortedArrayIII(int[] nums, int m) {
if (nums.length == 0) {
return 0;
}
int writeIndex = 1;
int countDuplicates = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i-1]) {
nums[writeIndex++] = nums[i];
countDuplicates = 1;
} else {
if (countDuplicates < m) {
nums[writeIndex++] = nums[i];
countDuplicates++;
}
}
}
return writeIndex;
}