提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章来源:https://www.toymoban.com/news/detail-739289.html
前言
双指针技巧处理数组问题,常用的是左右指针,和快慢指针
文章来源地址https://www.toymoban.com/news/detail-739289.html
一、力扣26. 删除有序数组中的重复项
class Solution {
public int removeDuplicates(int[] nums) {
int i, j;
for(i = 0,j = 0; j < nums.length;){
if(nums[i] == nums[j]){
j ++;
}else{
nums[++i] = nums[j++];
}
}
return i + 1;
}
}
二、力扣83. 删除排序链表中的重复元素
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null)return null;
ListNode pre = head, p = head;
while(p != null){
if(p.val == pre.val){
p = p.next;
}else{
pre.next = p;
pre = pre.next;
p = p.next;
}
}
pre.next = null;
return head;
}
}
三、力扣27. 移除元素
class Solution {
public int removeElement(int[] nums, int val) {
if(nums.length == 0){
return 0;
}
int i , j;
for(i = 0, j = 0; j < nums.length;){
if(nums[j] == val){
j ++;
}else{
nums[i++] = nums[j++];
}
}
return i;
}
}
四、力扣283. 移动零
class Solution {
public void moveZeroes(int[] nums) {
for(int i = 0,j = 0; j < nums.length;){
if(nums[j] == 0){
j ++;
}else{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i ++;
j ++;
}
}
}
}
五、力扣167. 两数之和 II - 输入有序数组
class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
for(int left = 0, right = numbers.length-1; left < right;){
int cur = numbers[left] + numbers[right];
System.out.println(cur);
if(cur > target){
right --;
}else if(cur < target){
left ++;
}else{
res[0] = left+1;
res[1] = right+1;
break;
}
}
return res;
}
}
六、力扣344. 反转字符串
class Solution {
public void reverseString(char[] s) {
for(int i = 0, j = s.length-1; i < j; i ++,j--){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
七、力扣最长回文子串
class Solution {
String res;
int count = 1;
public String longestPalindrome(String s) {
res = s.substring(0,1);
for(int i = 0; i <s.length(); i ++){
fun(s,i,i);
if(i + 1 < s.length()){
fun(s,i , i + 1);
}
}
return res;
}
public void fun(String s, int left, int right){
while(left >=0 && right < s.length()){
if(s.charAt(left) == s.charAt(right)){
left --;
right ++;
}else{
break;
}
}
left ++;
right --;
if((right - left + 1) > count){
count = right - left + 1;
res = s.substring(left,right+1);
}
}
}
到了这里,关于力扣labuladong——一刷day18的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!