1.python
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
# 使用两个指针分别指向数组头和尾,最差的结果是把数组都遍历一遍,时间复杂度为O(N),引入了两个额外变量,空间复杂度为O(1)
start = 0
end = len(numbers) - 1
#while(True):
while(start < end):
if (numbers[start] + numbers[end] == target):
return [start+1, end+1]
elif(numbers[start] + numbers[end] > target):
end -= 1
else:
start += 1
2.java
class Solution {
public int[] twoSum(int[] numbers, int target) {
int start = 0;
int end = numbers.length - 1;
while(start < end){
if (numbers[start] + numbers[end] == target){
return new int[]{
start + 1, end + 1};
}
else if(numbers[start] + numbers[end] > target){
end--;
}
else{
start++;
}
}
// 不要忘记写return
return null;
}
}
为什么可以用双指针?
可以看成是从0-c的有序数组中找到两个数使得两数平方和=target
1.python
class Solution(object):
def judgeSquareSum(self, c):
"""
:type c: int
:rtype: bool
"""
# 可以看成是从0-c的有序数组中找到两个数使得两数平方和=target
# 时间复杂度:O(n),空间复杂度O(1)
start = 0
# 一定要转换为int
end = int(math.sqrt(c))
# 加等号是因为当c=2时,返回true,证明两个数可以相等,两个指针可以相遇。
while (start <= end):
s = (start * start) + (end * end)
if(s == c):
return True
elif(s > c):
end = end - 1
else:
start = start + 1
return False
2.java
class Solution {
public boolean judgeSquareSum(int c) {
int start = 0;
int end = (int)Math.sqrt(c);
while(start <= end){
int s = start * start + end * end;
if(s == c){
return true;
}else if(s > c){
end--;
}else{
start++;
}
}
return false;
}
}
1.python
class Solution(object):
def reverseVowels(self, s)