算法类

双指针

two sum

  • 有序数组中查找和为 target 的索引+1数组

twoSum

  1. class Solution {
  2. public int[] twoSum(int[] numbers, int target) {
  3. if (numbers == null || numbers.length == 0) {
  4. return null;
  5. }
  6. int startIndex = 0;
  7. int lastIndex = numbers.length - 1;
  8. int sum = 0;
  9. for (int i = 0; i < numbers.length; i++) {
  10. sum = numbers[startIndex] + numbers[lastIndex];
  11. if (sum < target) {
  12. startIndex++;
  13. } else if (sum > target) {
  14. lastIndex--;
  15. } else {
  16. return new int[]{startIndex+1, lastIndex+1};
  17. }
  18. }
  19. return null;
  20. }
  21. }

平方数之和

平方数之和

  • 二分法

  • 双指针

    1. class Solution {
    2. public boolean judgeSquareSum(int c) {
    3. if (c < 0) {
    4. return false;
    5. }
    6. int first = 0;
    7. int last = (int)Math.sqrt(c);
    8. int sum = 0;
    9. while (first <= last) {
    10. sum = first * first + last * last;
    11. if (sum < c) {
    12. first++;
    13. } else if (sum > c) {
    14. last--;
    15. } else {
    16. return true;
    17. }
    18. }
    19. return false;
    20. }
    21. }

反转字符串中的元音字母

  • 注意元音字母有大写
  • 是元音和元音的反转
  • 左右指针往中间查找

    • 注意 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) {

      1. firstCh = result[first];
      2. lastCh = result[last];
      3. if (!isVowel(firstCh)) {
      4. first++;
      5. continue;
      6. }
      7. if (!isVowel(lastCh)) {
      8. last--;
      9. continue;
      10. }
      11. temp = result[first];
      12. result[first] = result[last];
      13. result[last] = temp;
      14. first++;
      15. last--;

      } return new String(result); }

      private boolean isVowel(char c) { switch (c) {

      1. case 'a':
      2. case 'A':
      3. case 'e':
      4. case 'E':
      5. case 'i':
      6. case 'I':
      7. case 'o':
      8. case 'O':
      9. case 'u':
      10. case 'U':
      11. return true;
      12. default:
      13. return false;

      } }

} ```