[LeetCode] 27. 移除元素
双指针基础应用.
class Solution {
public int removeElement(int[] nums, int val) {
int slowIndex = 0;
for (int fastIndex = slowIndex; fastIndex < nums.length; fastIndex++) {
if (nums[fastIndex] != val) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
}
[LeetCode] 26. 删除有序数组中的重复项
class Solution {
public int removeDuplicates(int[] nums) {
int slowIndex = 0;
for (int fastIndex = 1; fastIndex < nums.length; fastIndex++) {
if (nums[fastIndex] != nums[slowIndex]) {
nums[++slowIndex] = nums[fastIndex];// 这里 slowIndex 是先加
}
}
return slowIndex + 1;
}
}
[LeetCode] 283. 移动零
本质上都是通过双指针, 把后面的元素往前移动.
class Solution {
public void moveZeroes(int[] nums) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
if (nums[fastIndex] != 0) {
nums[slowIndex++] = nums[fastIndex];
}
}
for (int i = slowIndex; i < nums.length; i++) {
nums[i] = 0;
}
}
}
[LeetCode] 844. 比较含退格的字符串
这一题二刷的时候依旧不会做, 一开始先入为主认为在双指针的题目下, 这一题肯定也是快慢指针的写法. 过程中发现异常的时候也意识到要从后向前遍历, 然而想着这样写会比较复杂, 时间复杂度不知道是否能满足, 脑子就乱了. 因此一定要意识到, 双指针不是只有快慢指针, 也不一定是从前往后遍历, 需要具体问题具体分析.
class Solution {
public boolean backspaceCompare(String s, String t) {
int sIndex = s.length() - 1;
int tIndex = t.length() - 1;
int sSkipCount = 0;
int tSkipCount = 0;
while (sIndex >= 0 || tIndex >= 0) {
while (sIndex >= 0) {
if (s.charAt(sIndex) == '#') {
sSkipCount++;// 累计一下有多少个退格键
} else if (sSkipCount > 0) {
sSkipCount--;// 后面通过减小 sIndex 的方式把字母删除
} else {
break;// 当前有效字符所在的索引已经找到
}
sIndex--;
}
while (tIndex >= 0) {
if (t.charAt(tIndex) == '#') {
tSkipCount++;// 累计一下有多少个退格键
} else if (tSkipCount > 0) {
tSkipCount--;// 后面通过减小 tIndex 的方式把字母删除
} else {
break;// 当前有效字符所在的索引已经找到
}
tIndex--;
}
if (sIndex < 0 && tIndex < 0) {
// 两个字符串所有的字符都比对过了
return true;
} else if (sIndex < 0 || tIndex < 0 || s.charAt(sIndex) != t.charAt(tIndex)) {
// 如果一个字符串已经遍历完毕, 另一个字符串还有没比对的字符
// 或者两个字符串都没遍历完毕, 但是字符已经不一样了
return false;
} else {
// 跳过当前相同的字符
sIndex--;
tIndex--;
}
}
return true;
}
}
[LeetCode] 977. 有序数组的平方
一开始尝试复用原始的数组, 发现不行, 一定要新创建一个数组.
这一题的本质在于, 一个排好序的非降序数组, 从最左边往中间(存在负数的情况), 从最右边往中间, 数字的平方是在递减的. 因此利用双指针, 每次把平方大的数, 放在新创建的数组的末尾, 数组的末尾指针往前移动即可.
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int index = nums.length - 1;
int[] result = new int[nums.length];
while (left <= right) {
if (Math.abs(nums[left]) >= Math.abs(nums[right])) {
result[index--] = nums[left] * nums[left++];
} else {
result[index--] = nums[right] * nums[right--];
}
}
return result;
}
}