1.前言
今天还是继续说leetcode(重磅消息:预计下周出动态规划教程,西安赶紧快出的,点赞+评论)
2.Leetcode14 最长公共前缀
这道题只需要通过循环遍历开头,直到不满足即可。
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
String ans = strs[0];
for(int i =1;i<strs.length;i++) {
int j=0;
for(;j<ans.length() && j < strs[i].length();j++) {
if(ans.charAt(j) != strs[i].charAt(j))
break;
}
ans = ans.substring(0, j);
if(ans.equals(""))
return ans;
}
return ans;
}
}
3.Leetcode15 三数之和(*)
这道题需要让nums[i]+nums[j]+nums[k]=0nums[i]+nums[j]+nums[k]=0nums[i]+nums[j]+nums[k]=0
首先三个数,我们第一个数遍历,剩下两个可以使用双指针。
整体的时间复杂度为O(n2)O(n^2)O(n2)
Tips1:双指针需要有一个条件调整
left和right指针,我们可以把数组排序
Tips2:排完序后,
[-1,1,-1,2]会变成[-1,-1,1,2]我们发现两个-1重复了,我们可以把nums[i]与nums[i-1]判断,如果重复,就可以continue跳过
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; // 跳过重复的第一个元素
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum < 0) left++;
else if (sum > 0) right--;
else {
// 这里内部寻找其他解
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++; // 跳过重复的 left
while (left < right && nums[right] == nums[right - 1]) right--; // 跳过重复的 right
left++;
right--;
}
}
}
return res;
}
}
4.Leetcode17 电话号码的字符组合
首先先对应字典(这里为了方便,使用python)
phoneMap = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
整体思路是通过递归给末尾增加元素的一种可能。

写出递归代码
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return list()
phoneMap = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
def backtrack(index: int):
if index == len(digits): # 递归后到这里
combinations.append("".join(combination)) # 一次完成后加入到总的
else:
digit = digits[index] # 找到元素
for letter in phoneMap[digit]: # 遍历每一个字母
combination.append(letter) # 加入
backtrack(index + 1) # 递归,加入下一个元素
combination.pop() # 完成,移除元素
combination = list()
combinations = list()
backtrack(0)
return combinations
5.结语
可以把11-20都做了
下期出动态规划,点赞评论谢谢!
293

被折叠的 条评论
为什么被折叠?



