Leetcode 167
题目描述:在有序数组中找出两个数,使它们的和为 target。
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
思路:
1.暴力。
两层for循环解决问题,时间复杂度为O(n^2);
2.双指针思想。
建立两个指针i和j分别指向数组中较小的元素和较大的元素,分别从正向和反向进行遍历。
因其为有序数组,值从小到大排列,故有以下三种情况:
- 当前指针所指两个值的和大于期望值,则需要降低和值,j左移即可;
- 当前指针所指两个值的和小于期望值,则需要增加和值,i右移即可;
- 当前指针所指两个值的和小于期望值,返回此刻的i和j;
注意规定控制条件:i < j。
时间复杂度为O(n)。
public class lc167 {
public static int[] twoSum(int[] numbers, int target) {
int i = 0;
int j = numbers.length - 1;
while (i < j){
int sum = numbers[i]+numbers[j];
if(sum == target){
i++;
j++;
break;
}else if(sum>target){
j--;
}else{
i++;
}
}
return new int[]{i,j};
}
public static void main(String[] args) {
int[] num = new int[]{2, 7, 11, 15};
int[] twoNum = new int[2];
twoNum = twoSum(num,26);
System.out.println(twoNum[0] +" " + twoNum[1]);
}
}
Leetcode 633
题目描述:判断一个非负整数是否为两个整数的平方和。
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
思路:
1.暴力。
两层for循环解决问题,时间复杂度为O(n^2);
2.双指针思想。
思路同上题。注意指针j的赋值。时间复杂度为O(n)。
public class lc633 {
public static boolean judgeSquareSum(int c) {
int i = 0;
int j = (int) Math.sqrt(c);
while (i <= j){
int sum = i*i + j*j;
if(sum == c){
return true;
}else if(sum>c){
j--;
}else{
i++;
}
}
return false;
}
public static void main(String[] args) {
boolean result = judgeSquareSum(4);
System.out.println(result);
}
}
Leetcode 345
题目描述:编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
思路:
1.暴力。
两层for循环解决问题,时间复杂度为O(n^2)。
2.双指针思想。
思路同上。涉及到集合、字符串和字符数组相互转换的相关操作。时间复杂度为O(n)。
public class lc345 {
public static String reverseVowels(String s) {
List<Character> list = Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
char[] str = s.toCharArray();
int i = 0;
int j = str.length - 1;
while (i <= j) {
if (!list.contains(str[i])) {
i++;
} else if (!list.contains(str[j])) {
j--;
} else {
char c = str[i];
str[i] = str[j];
str[j] = c;
i++;
j--;
}
}
return String.valueOf(str);
}
public static void main(String[] args) {
System.out.println(reverseVowels("leetcode"));
}
}