参考CS-Notes
算法思想相关
1.双指针
-
class Solution {
public int[] twoSum(int[] numbers, int target) {
int l = 0;
int r = numbers.length-1;
while(true) {
if(numbers[l]+numbers[r] < target) {
l++;
} else if (numbers[l]+numbers[r] > target) {
r--;
} else {
break;
}
}
return new int [] {l+1,r+1};
}
}
-
class Solution {
public boolean judgeSquareSum(int c) {
int i = 0;
int j = (int) Math.sqrt(c);
int res = 0;
boolean flag = false;
while (i <= j) {
res = i*i + j*j;
if (res == c) {
flag = true;
break;
} else if (res < c) {
i ++;
} else {
j --;
}
}
return flag;
}
}
-
class Solution {
public String reverseVowels(String s) {
if(s == null) return null;
int i = 0;
int j = s.length()-1;
HashSet<Character> vowels = new HashSet<> (
Arrays.asList('a','e','i','o','u','A','E','I','O','U')
);
char result[] = s.toCharArray();
while(i<=j) {
while (i<j && !vowels.contains(result[i])) {
i++;
}
while(i<j && !vowels.contains(result[j])) {
j--;
}
char tmp = result[i];
result[i] = result[j];
result[j] = tmp;
i++;
j--;
}
return new String(result);
}
}
-
class Solution {
public boolean isHW(String s,int i,int j) {
while(i<j) {
if(s.charAt(i) != s.charAt(j)) {
return false;
}
i ++;
j --;
}
return true;
}
public boolean validPalindrome(String s) {
int i = 0;
int j = s.length()-1;
boolean flag = true;
while(i<j) {
if(s.charAt(i) != s.charAt(j)) {
return isHW(s,i+1, j) || isHW(s, i, j-1);
}
i++;
j--;
}
return true;
}
}
-
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m-1;
int j = n-1;
int ij = m+n-1;
while(i>=0 || j>=0) {
if(i<0) {
nums1[ij--] = nums2[j--];
} else if(j<0){
nums1[ij--] = nums1[i--];
} else {
if(nums1[i] > nums2[j]) {
nums1[ij--] = nums1[i--];
} else {
nums1[ij--] = nums2[j--];
}
}
}
}
}
-
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode rb = head.next;
ListNode tt = head;
while (rb != tt) {
if(rb == null || rb.next == null) return false;
rb = rb.next.next;
tt = tt.next;
}
return true;
}
}
-
class Solution {
private boolean isSub(String s,String d) {
int i=0;
int j=0;
while (i<s.length() && j<d.length()) {
if(s.charAt(i++) == d.charAt(j)) {
j ++;
}
}
return j == d.length();
}
public String findLongestWord(String s, List<String> d) {
String result = "";
int maxLen = 0;
for (String x : d) {
if(isSub(s, x)) {
if(maxLen < x.length()) {
maxLen = x.length();
result = x;
} else if(maxLen == x.length() && result.compareTo(x) > 0) {
result = x;
}
}
}
return result;
}
}
双指针的题,一般都要从两个端点同步遍历数据,通过协调两个指针的移动与否来满足题目要求。