删除有序数组中的重复项
重点在于++p1
class Solution {public int removeDuplicates(int[] nums) {if(nums.length==0) return 0;int p1=0,p2=1;while(p2<nums.length){if(nums[p2]!=nums[p1]){nums[++p1]=nums[p2++];}else p2++;}return p1+1;}
}
class Solution {public void moveZeroes(int[] nums) {int slow=0,fast=0;while(fast<nums.length){if(nums[fast]!=0){nums[slow++]=nums[fast++];}else fast++;}for(int i=slow;i<nums.length;i++){nums[i]=0;}return;}
}
两数之和 -输入有序数组
只要数组有序,就应该想到双指针技巧。
class Solution {public int[] twoSum(int[] numbers, int target) {int left=0,right=numbers.length-1;while(left<=right){int sum=numbers[left]+numbers[right];if(sum==target){return new int[]{left+1,right+1};}else if(sum<target){left++;}else{right--;}}return new int[]{-1,-1};}
}
直接创建新数组来表示结果
最长回文子串(分奇偶串
以一个数为中心,或者以两个数为中心!
class Solution {public String longestPalindrome(String s) {String res="";for(int i=0;i<s.length();i++){String s1=palindrome(s,i,i);//以i为中心String s2=palindrome(s,i,i+1);//两个数为中心res=res.length()>s1.length()?res:s1;res=res.length()>s2.length()?res:s2;}return res;}String palindrome(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);//最后一次不满足,则回退,substring左闭右开}
}