167.两数之和 II - 输入有序数组
给定一个已按照升序排列的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
错误1:没写 return null;
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){
return new int[]{i + 1,j + 1};
}else if(sum < target){
i++;
}else{
j--;
}
}
return null;
}
}
633.平方数之和
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3
输出: False
错误1int i = 0,j = Math.sqrt©;
Line 3: error: incompatible types: possible lossy conversion from double to int
错误2while (i <= j)
输入2,预期是true,结果是false。
class Solution {
public boolean judgeSquareSum(int c) {
int i = 0,j = (int) Math.sqrt(c);
while (i <= j) {
int powSum = i * i + j * j;
if(powSum == c){
return true;
}else if(powSum < c){
i++;
}else{
j--;
}
}
return false;
}
}
345. 反转字符串中的元音字母
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: “hello”
输出: “holle”
示例 2:
输入: “leetcode”
输出: “leotcede”
说明:
元音字母不包含字母"y"。
元音字母:a e i o u A E I O U
错误1: char[] result = new char[s.length];
Line 6: error: cannot find symbol: variable length
错误2: while (i < j ){
错误3:提交超出时间限制
class Solution {
private final static HashSet vowels = new HashSet<>(Arrays.asList(‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’, ‘O’, ‘U’));
public String reverseVowels(String s) {
int i = 0,j = s.length() - 1;
char[] result = new char[s.length()];
while (i <= j ) {
char ci = s.charAt(i);
char cj = s.charAt(j);
if (!vowels.contains(ci)){
result[i++] = ci;
} else if (!vowels.contains(cj)) {
result[i--] = cj;
} else {
result[i++] = cj;
result[j--] = ci;
}
}
return new String(result);
}
}
680. 验证回文字符串 Ⅱ
给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。
示例 1:
输入: “aba”
输出: True
示例 2:
输入: “abca”
输出: True
解释: 你可以删除c字符。
注意:
字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。