Leetcode: 167. Two Sum II - Input array is sorted (Easy)
从一个已经排序的数组中查找出两个数,使它们的和为 0
Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
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;}
Leetcode: 345. Reverse Vowels of a String (Easy)
Given s = “leetcode”, return “leotcede”.
private HashSet<Character> vowels = new HashSet<>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));public String reverseVowels(String s) {if(s.length() == 0) return 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;i++;} else if(!vowels.contains(cj)){result[j] = cj;j--;} else{result[i] = cj;result[j] = ci;i++;j--;}}return new String(result);}
Leetcode: 633. Sum of Square Numbers (Easy)
Input: 5 Output: True Explanation: 1 1 + 2 2 = 5
public boolean judgeSquareSum(int c) {
int left = 0, right = (int) Math.sqrt(c);
while(left <= right){
int powSum = left * left + right * right;
if(powSum == c) return true;
else if(powSum > c) right--;
else left++;
}
return false;
}
Leetcode: 680. Valid Palindrome II (Easy)
Input: “abca” Output: True Explanation: You could delete the character ‘c’.
public boolean validPalindrome(String s) {
int i = 0, j = s.length() - 1;
while(i < j){
if(s.charAt(i) != s.charAt(j)){
return isPalindrome(s, i, j - 1) || isPalindrome(s, i + 1, j);
}
i++;
j--;
}
return true;
}
private boolean isPalindrome(String s, int l, int r){
while(l < r){
if(s.charAt(l) != s.charAt(r))
return false;
l++;
r--;
}
return true;
}
补充 Leetcode: 125 Valid Palindrome I (Easy)
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写
public boolean isPalindrome(String s) {
StringBuffer sgood = new StringBuffer();
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(Character.isLetterOrDigit(ch)){
sgood.append(Character.toLowerCase(ch));
}
}
StringBuffer sgood_rev = new StringBuffer(sgood).reverse();
return sgood.toString().equals(sgood_rev.toString());
}
