双指针技巧数组题目

题目 难度 要点
删除有序数组中的重复项 快指针与慢指针值不同,那么应该将值放在慢指针下一位
移除元素 快指针对应值若不需移除,那么应该将值放在当前慢指针
最长回文子串 以当前位置或者当前位置及相邻位置扩散寻找回文子串

删除有序数组中的重复项

class Solution {
public int removeDuplicates(int[] nums) {
int slow = 0;
int fast = 0;
while (fast < nums.length) {
if (nums[slow] != nums[fast]) {
slow++;
nums[slow] = nums[fast];
}
fast++;
}
return slow + 1;
}
}

移除元素

class Solution {
public int removeElement(int[] nums, int val) {
int left = 0, right = 0;
while (right < nums.length) {
if (nums[right] != val) {
nums[left] = nums[right];
left++;
}
right++;
}
return left;
}
}

最长回文子串

class Solution {
public String longestPalindrome(String s) {
String res = "";
for (int i = 0; i < s.length(); i++) {
String s1 = getPalindrome(s, i, i);
String s2 = getPalindrome(s, i, i + 1);
res = res.length() < s1.length()? s1: res;
res = res.length() < s2.length()? s2: res;
}
return res;
}
private String getPalindrome(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return s.substring(left + 1, right);
}
}
posted @   kiper  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示