当前位置:网站首页>【力扣刷题】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怎么每次这么低,不过没瓜西,加油哈哈哈哈哈
边栏推荐
- The 8th Blue Bridge Cup single chip microcomputer provincial competition
- "Analysis of 43 cases of MATLAB neural network": Chapter 41 implementation of customized neural network -- personalized modeling and Simulation of neural network
- The 10th Blue Bridge Cup single chip microcomputer provincial competition
- Kotlin基础学习 17
- In depth interpretation of pytest official documents (26) customized pytest assertion error information
- Pointer array & array pointer
- Global and Chinese markets for electronic laryngoscope systems 2022-2028: Research Report on technology, participants, trends, market size and share
- 0 foundation how to learn automated testing? Follow these seven steps step by step and you will succeed
- 蓝桥杯单片机省赛第六届
- 数据库文件逻辑结构形式指的是什么
猜你喜欢

Oracle的md5

初识string+简单用法(二)

一天上手Aurora 8B/10B IP核(5)----从Framing接口的官方例程学起
![[personal notes] PHP common functions - custom functions](/img/3d/d50622e3ddb08f654f30063e8226ac.jpg)
[personal notes] PHP common functions - custom functions

Getting started with MQ

Knowing things by learning | self supervised learning helps improve the effect of content risk control

Pycharm2021 delete the package warehouse list you added

Review materials of project management PMP high frequency examination sites (8-1)

u本位合约爆仓清算解决方案建议

高性能 低功耗Cortex-A53核心板 | i.MX8M Mini
随机推荐
Aaaaaaaaaaaa
Failed to upgrade schema, error: “file does not exist
"Analysis of 43 cases of MATLAB neural network": Chapter 42 parallel operation and neural network - parallel neural network operation based on cpu/gpu
Custom classloader that breaks parental delegation
Discrimination between sap Hana, s/4hana and SAP BTP
蓝桥杯单片机省赛第十一届第二场
This article describes the step-by-step process of starting the NFT platform project
Review materials of project management PMP high frequency examination sites (8-1)
【无线图传】基于FPGA的简易无线图像传输系统verilog开发,matlab辅助验证
Detailed explanation of ThreadLocal
[数据库]JDBC
Get started with Aurora 8b/10b IP core in one day (5) -- learn from the official routine of framing interface
Exchange rate query interface
VS2010 plug-in nuget
ImageAI安装
《MATLAB 神经网络43个案例分析》:第41章 定制神经网络的实现——神经网络的个性化建模与仿真
Kotlin basic learning 14
Kotlin basic learning 13
The first game of the 11th provincial single chip microcomputer competition of the Blue Bridge Cup
KL divergence is a valuable article