当前位置:网站首页>【力扣刷题】15.三数之和(双指针);17.电话号码的字母组合(递归回溯)
【力扣刷题】15.三数之和(双指针);17.电话号码的字母组合(递归回溯)
2022-07-02 03:38:00 【李小恩恩子】
目录
15.三数之和
题目:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/3sum
解题思路:
给我一个数组,判断是否存在三个元素之和等于0,找出所有不重复元素的三元组。我开始想的是既然要不重复,那就利用哈希表来判断是否包含某一个三元组,有的话就不加入答案里面,没有的话加入。因为是三元组,要从数组里面选出三个元素,时间复杂度最高的也需要O(n³),再优化一下:一层for循环之后另外两个元素用双指针(当固定了其中两个元素a和b之后,剩下的那个元素c一定是唯一的使a+b+c=0,所以可以进行排序+双指针来实现)来选,那就是O(n²),那就需要首先直接对数组进行排序处理,排序时间复杂度也是O(n²)。所以这个题目时间复杂度为O(n²)。
因为会对数组元素进行排序,利用一层for循环固定了一个元素a之后,剩下的b和c一定会朝数组中间运动,直到左右指针相遇。当a+b+c=0时,一个指针移动时,另外一个指针一定也要移动,left++和right--;>0,向左移动右指针,调小那个正数right--;<0,向右移动左指针,调大那个负数left++。
代码:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if(nums.length < 3) return new LinkedList<>();
//对数组进行排序
Arrays.sort(nums);
List<List<Integer>> res = new LinkedList<>();
//利用哈希表判重
HashMap<List<Integer>,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length - 2;i++){
//双指针
int left = i + 1,right = nums.length - 1;
while(left < right){
if(nums[i]+nums[left]+nums[right] == 0){
List<Integer> list = new LinkedList<Integer>();
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
if(map.containsKey(list)){
left++;
right--;
continue;
}else{
map.put(list,1);
res.add(list);
left++;
right--;
}
}else if(nums[i]+nums[left]+nums[right] > 0){
right--;
}else{
left++;
}
}
}
return res;
}
}
然后发现,只击败了5.29%哈哈哈哈哈哈。
优化:
然后优化了一下,其实这一题不需要利用哈希表判重了,因为使用了排序之后,重复的元素会挨在一起,我上一重循环已经挑选过了,那就不需要对相同的元素再进行一次挑选,直接跳过即可。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if(nums.length < 3) return new LinkedList<>();
//对数组进行排序
Arrays.sort(nums);
List<List<Integer>> res = new LinkedList<>();
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){
//连续相同元素,挑选过了,跳
if(left > i + 1 && nums[left] == nums[left - 1]) {
left++;
continue;
}
if(nums[i]+nums[left]+nums[right] == 0){
List<Integer> list = new LinkedList<Integer>();
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
res.add(list);
left++;
right--;
}else if(nums[i]+nums[left]+nums[right] > 0){
right--;
}else{
left++;
}
}
}
return res;
}
}
17.电话号码的字母组合
题目:
解题思路:
因为不知道它输入的数字会包含几位数,于是不能确定使用几层for循环,于是想到了可以用递归+回溯来实现,和求解迷宫很像。
将每位数字对应的字符串保存下来,刚好利用0和1没有对应字符,于是数字2-9直接对应下标2-9。用一个全局类变量保存答案。
dfs方法的参数:digits字符串,digits的长度,当前遍历到哪个数字(终点:count==n),答案字符串。
代码很好写,注意回溯。
ans += cur.charAt(i);
dfs(digits,n,count + 1,ans);
//回溯
ans = ans.substring(0,ans.length()-1);
代码:
class Solution {
String[] s = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> res = new LinkedList<String>();
public List<String> letterCombinations(String digits) {
if(digits.length()==0) return new LinkedList<String>();
int n = digits.length();
dfs(digits,n,0,"");
return res;
}
//参数为①digits,②digits的长度,③当前遍历了几个数字(从0开始,加入res的判断为count==n),④答案字符串
public void dfs(String digits,int n,int count,String ans){
//递归的终点
if(count == n){
res.add(ans);
return;
}
int index = Integer.parseInt(""+digits.charAt(count));
String cur = s[index];
for(int i = 0; i < cur.length();i++){
ans += cur.charAt(i);
dfs(digits,n,count + 1,ans);
ans = ans.substring(0,ans.length()-1);
}
}
}
ovo怎么每次这么低,不过没瓜西,加油哈哈哈哈哈
边栏推荐
- [HCIA continuous update] overview of dynamic routing protocol
- Global and Chinese market of gynaecological health training manikin 2022-2028: Research Report on technology, participants, trends, market size and share
- leetcode-1380. Lucky number in matrix
- "Analysis of 43 cases of MATLAB neural network": Chapter 41 implementation of customized neural network -- personalized modeling and Simulation of neural network
- Kotlin basic learning 14
- Pycharm2021 delete the package warehouse list you added
- 高性能 低功耗Cortex-A53核心板 | i.MX8M Mini
- NLog use
- Blue Bridge Cup SCM digital tube skills
- MySQL之账号管理
猜你喜欢
Oracle的md5
蓝桥杯单片机省赛第七届
Large screen visualization from bronze to the advanced king, you only need a "component reuse"!
One of the future trends of SAP ui5: embrace typescript
毕设-基于SSM电影院购票系统
ThreadLocal详解
焱融看 | 混合云时代下,如何制定多云策略
The second game of the 11th provincial single chip microcomputer competition of the Blue Bridge Cup
[HCIA continuous update] working principle of OSPF Protocol
u本位合约爆仓清算解决方案建议
随机推荐
What kind of interview is more effective?
高性能 低功耗Cortex-A53核心板 | i.MX8M Mini
Homework in Chapter 3 of slam course of dark blue vision -- derivative application of T6 common functions
u本位合约爆仓清算解决方案建议
VS2010 plug-in nuget
接口调试工具模拟Post上传文件——ApiPost
Global and Chinese market of bone adhesives 2022-2028: Research Report on technology, participants, trends, market size and share
Getting started with MQ
JIT deep analysis
Retrofit's callback hell is really vulnerable in kotlin synergy mode
蓝桥杯单片机省赛第七届
潘多拉 IOT 开发板学习(HAL 库)—— 实验2 蜂鸣器实验(学习笔记)
ImageAI安装
跳出舒适区,5年点工转型自动化测试工程师,我只用了3个月时间
The 5th Blue Bridge Cup single chip microcomputer provincial competition
Knowing things by learning | self supervised learning helps improve the effect of content risk control
Review materials of project management PMP high frequency examination sites (8-1)
Global and Chinese market of X-ray detectors 2022-2028: Research Report on technology, participants, trends, market size and share
In depth interpretation of pytest official documents (26) customized pytest assertion error information
蓝桥杯单片机省赛第九届