本文将持续更新
- 两数之和 II - 输入有序数组
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
class Solution {
public int[] twoSum(int[] numbers, int target) {
int i = 0;
int j = numbers.length - 1;
int[] result = new int[2];
while (i < j) {
if (i < j && numbers[i] + numbers[j] > target) {
j--;
} else if (i < j && numbers[i] + numbers[j] < target) {
i++;
} else {
result[0] = i+1;
result[1] = j+1;
return result;
}
}
return null;
}
}
- 反转字符串中的元音字母
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: "hello"
输出: "holle"
示例 2:
输入: "leetcode"
输出: "leotcede"
import java.util.HashSet; //leetcode submit region begin(Prohibit modification and deletion) class Solution {public String reverseVowels(String s) {if(s == "" || s==null)return s;int i = 0;int j = s.length() - 1;HashSet<Character> set = new HashSet<>();set.add('a');set.add('e');set.add('i');set.add('o');set.add('u');set.add('A');set.add('E');set.add('I');set.add('O');set.add('U');char[] chs = s.toCharArray();while (i < j) {while (i < j && !set.contains(chs[i])) {i++;}while (i < j && !set.contains(chs[j])) {j--;}if (i < j) {char temp;temp = chs[i];chs[i] = chs[j];chs[j] = temp;i++;j--;}}return new String(chs);} }
-
验证回文字符串 Ⅱ
给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。
示例 1:
输入: "aba"
输出: True
示例 2:
输入: "abca"
输出: True
解释: 你可以删除c字符。
注意:
1. 字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。
class Solution {public boolean validPalindrome(String s) {for (int i = 0, j = s.length() - 1; i < j; i++, j--) {if (s.charAt(i) != s.charAt(j)) {return check(s, i + 1, j) || check(s, i, j - 1);}}return true;}public boolean check(String s, int i, int j) {while (i < j) {if (s.charAt(i++) != s.charAt(j--)) {return false;}}return true;} }
- 两数平方和
class
solution{
public boolean
judgeSquareSum(
int
c) {
int
i =
0
; 存在直接可以开平方的情况
int
j = Math.sqrt(c)
;
while
(i <= j) {
int
sum = i * i + j * j
;
if
(sum == c)
return true;
if
(sum > c)
j--
;
else
i++
;
}
}
}