算法类
双指针
two sum
- 有序数组中查找和为 target 的索引+1数组
class Solution {
public int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length == 0) {
return null;
}
int startIndex = 0;
int lastIndex = numbers.length - 1;
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = numbers[startIndex] + numbers[lastIndex];
if (sum < target) {
startIndex++;
} else if (sum > target) {
lastIndex--;
} else {
return new int[]{startIndex+1, lastIndex+1};
}
}
return null;
}
}
平方数之和
二分法
双指针
class Solution {
public boolean judgeSquareSum(int c) {
if (c < 0) {
return false;
}
int first = 0;
int last = (int)Math.sqrt(c);
int sum = 0;
while (first <= last) {
sum = first * first + last * last;
if (sum < c) {
first++;
} else if (sum > c) {
last--;
} else {
return true;
}
}
return false;
}
}
反转字符串中的元音字母
- 注意元音字母有大写
- 是元音和元音的反转
左右指针往中间查找
注意 continue 的使用 ```java class Solution { public String reverseVowels(String s) { char[] result = s.toCharArray(); int first = 0; int last = s.length()-1; char firstCh; char lastCh; char temp; while (first < last) {
firstCh = result[first];
lastCh = result[last];
if (!isVowel(firstCh)) {
first++;
continue;
}
if (!isVowel(lastCh)) {
last--;
continue;
}
temp = result[first];
result[first] = result[last];
result[last] = temp;
first++;
last--;
} return new String(result); }
private boolean isVowel(char c) { switch (c) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return true;
default:
return false;
} }
} ```