双指针6个--力扣--java
程序员文章站
2022-05-06 21:35:18
...
题目1:
class Solution {
public int[] twoSum(int[] numbers, int target) {
int i=0,j=numbers.length-1;
while(i<j){
int sum=numbers[i]+numbers[j];
if(sum<target) i++;
else if(sum>target) j--;
else return new int[]{i+1,j+1};
}
return new int[]{-1,-1};
}
}
题目2:
class Solution {
public boolean judgeSquareSum(int c) {
int i=0,j=(int)Math.sqrt(c);
while(i<=j){
int sum=i*i+j*j;
if(sum==c) return true;
else if(sum<c) i++;
else j--;
}
return false;
}
}
题目3:
class Solution {
public String reverseVowels(String s) {
char []ch=s.toCharArray();
String yuan="aeiouAEIOU";
int i=0,j=ch.length-1;
while(i<j){
while(i<j&&yuan.indexOf(ch[i])== -1) i++;
while(i<j&&yuan.indexOf(ch[j])== -1) j--;
if(i<j){
char c;
c=ch[i];
ch[i]=ch[j];
ch[j]=c;
i++;
j--;
}
}
return new String(ch);
}
}
题目4:
class Solution {
public boolean validPalindrome(String s) {
int i=0,j=s.length()-1;
while(i<j){
if(s.charAt(i)!=s.charAt(j))
return isPalindrome(s,i+1,j)||isPalindrome(s,i,j-1);
i++;
j--;
}
return true;
}
public boolean isPalindrome(String s,int i,int j){
while(i<j){
if(s.charAt(i)!=s.charAt(j))
return false;
i++;
j--;
}
return true;
}
}
题目5:
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
for(int i=m,j=0;j<n;i++,j++){
nums1[i]=nums2[j];
}
Arrays.sort(nums1);
}
}
//2
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int len1=m-1;
int len2=n-1;
int len=m+n-1;
while(len1>=0&&len2>=0){
nums1[len--]=nums1[len1]>nums2[len2]?nums1[len1--]:nums2[len2--];
}
System.arraycopy(nums2,0,nums1,0,len2+1);
}
}
题目6:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast=head,slow=head;
//如果列表中不存在环,最终快指针将会最先到达尾部,此时我们可以返回 false
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast) return true;
}
return false;
}
}