当前位置:网站首页>【力扣刷题】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怎么每次这么低,不过没瓜西,加油哈哈哈哈哈
边栏推荐
- UI (New ui:: MainWindow) troubleshooting
- 汇率的查询接口
- Kotlin basic learning 17
- Pointer array & array pointer
- 【人员密度检测】基于形态学处理和GRNN网络的人员密度检测matlab仿真
- Kotlin basic learning 13
- [yolo3d]: real time detection of end-to-end 3D point cloud input
- 0 foundation how to learn automated testing? Follow these seven steps step by step and you will succeed
- Exchange rate query interface
- Set vscode. When double clicking, the selected string includes the $symbol - convenient for PHP operation
猜你喜欢

The 5th Blue Bridge Cup single chip microcomputer provincial competition

【小技巧】使用matlab GUI以对话框模式读取文件

MySQL index, transaction and storage engine

JIT deep analysis

High performance and low power cortex-a53 core board | i.mx8m Mini

Discrimination between sap Hana, s/4hana and SAP BTP
![[personal notes] PHP common functions - custom functions](/img/3d/d50622e3ddb08f654f30063e8226ac.jpg)
[personal notes] PHP common functions - custom functions

One of the future trends of SAP ui5: embrace typescript

What do you know about stock selling skills and principles

汇率的查询接口
随机推荐
The 11th Blue Bridge Cup single chip microcomputer provincial competition
蓝桥杯单片机省赛第十一届
Unity脚本的基础语法(7)-成员变量和实例化
JS generate random numbers
Account management of MySQL
[punch in] flip the string (simple)
Large screen visualization from bronze to the advanced king, you only need a "component reuse"!
[HCIA continuous update] working principle of OSPF Protocol
蓝桥杯单片机省赛第十二届第二场
Global and Chinese market of X-ray detectors 2022-2028: Research Report on technology, participants, trends, market size and share
"Analysis of 43 cases of MATLAB neural network": Chapter 42 parallel operation and neural network - parallel neural network operation based on cpu/gpu
Network connection mode of QT
数据库文件逻辑结构形式指的是什么
Kotlin基础学习 16
Pointer array & array pointer
Unity脚本的基础语法(8)-协同程序与销毁方法
Basic operations of MySQL database (based on tables)
Object oriented thinking
[yolo3d]: real time detection of end-to-end 3D point cloud input
The page in H5 shows hidden execution events