LeetCode 15. 3Sum--Java,Python解法
题目地址:
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],A solution set is:
[[-1, 0, 1],[-1, -1, 2]
]
谷歌翻译的题目:
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:
解决方案集不得包含重复的三元组。
我的思路是2重循环,算出a+b的所有可能,然后判断-(a+b)是否在列表里,时间复杂度是O(N^2)
Python解法:
class Solution:def threeSum(self, nums = [-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0]):nums.sort()length=len(nums)temp=[]temp4=set()a={}b={}for i in nums:if i not in a:a[i]=1else:a[i]+=1i=0while i<length:j=i+1while j<length:passif j>=i+2 and nums[j]==nums[j-1]:if nums[j]==nums[i]:i=j-2breakj+=1continueif nums[i] not in b:b[nums[i]]=set()if nums[j] in b[nums[i]]:j+=1continueelse:b[nums[i]].add(nums[j])temp2=-(nums[i]+nums[j])if temp2 in a :count=1if nums[i]==temp2:count+=1if nums[j]==temp2:count+=1if a[temp2]>=count:temp3=[nums[i],nums[j],temp2]temp3.sort()if str(temp3) not in temp4:temp4.add(str(temp3))temp.append([nums[i],nums[j],temp2])j+=1i+=1 for i in temp:i.sort()temp.sort()return temp
改进后的办法是两边向中间逼近:
class Solution:def threeSum(self, nums = [-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0]):res = []nums.sort()length = len(nums)for i in range(0,length-2): if nums[i]>0: break if i>0 and nums[i]==nums[i-1]: continue l, r = i+1, length-1 while l<r:total = nums[i]+nums[l]+nums[r]if total<0:l+=1elif total>0: r-=1else: res.append([nums[i], nums[l], nums[r]])while l<r and nums[l]==nums[l+1]:l+=1while l<r and nums[r]==nums[r-1]: r-=1l+=1r-=1return res
Java解法如下:
class Solution {public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> res = new ArrayList<>();Arrays.sort(nums);for (int i = 0; i + 2 < nums.length; i++) {if (i > 0 && nums[i] == nums[i - 1]) { // skip same resultcontinue;}int j = i + 1, k = nums.length - 1; int target = -nums[i];while (j < k) {if (nums[j] + nums[k] == target) {res.add(Arrays.asList(nums[i], nums[j], nums[k]));j++;k--;while (j < k && nums[j] == nums[j - 1]) j++; // skip same resultwhile (j < k && nums[k] == nums[k + 1]) k--; // skip same result} else if (nums[j] + nums[k] > target) {k--;} else {j++;}}}return res;
}
}
LeetCode 15. 3Sum--Java,Python解法相关推荐
- LeetCode 709 To Lower Case -- java,python解法
题目地址:To Lower Case - LeetCode Implement function ToLowerCase() that has a string parameter str, and ...
- LeetCode 3. Longest Substring Without Repeating Characters-- c++,java,python解法
题目地址: Given a string, find the length of the longest substring without repeating characters. Example ...
- LeetCode刷题之python解法(持续更新)
1. Two Sum 4行 class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:d = {}fo ...
- 【Leetcode】5 longestPalindrome python解法
leetcode第5题 longestPalindrome 最长回文子串 python解法 给定一个字符串 s,找到 s 中最长的回文子串.你可以假设 s 的最大长度为1000. 输入: " ...
- LeetCode - 15. 3Sum
15. 3Sum Problem's Link ---------------------------------------------------------------------------- ...
- LeetCode——15. 3Sum
一.题目链接:https://leetcode.com/problems/3sum/ 二.题目大意: 3和问题是一个比较经典的问题,它可以看做是由2和问题(见http://www.cnblogs.co ...
- [LeetCode]15. 3Sum
原题链接:https://leetcode.com/problems/3sum/description/ 意思是对给定的数组找到所有三个数加起来为0的数的下标 我的实现: class Solution ...
- 第十二届蓝桥杯第二期模拟赛(java) python解法
A 问题描述 小明要用二进制来表示 1 到 10000 的所有整数,要求不同的整数用不同的二进制数表示,请问,为了表示 1 到 10000 的所有整数,至少需要多少个二进制位? 结果:14 print ...
- leetcode——15.3Sum
#include<stdio.h> #include<stdlib.h>int** threeSum(int* nums, int numsSize, int* returnS ...
最新文章
- RFID中间件成为全球软件产业争夺新焦点
- 文思创新深圳招聘biztalk
- python文件打包成exe是 upx不可用、找不到py文件_使用PyInstaller将Python程序打包成一个单独的exe文件...
- LeetCode----9. 回文数
- Linux文本编辑跳到指定行,Linux 命令每日一练:vi命令
- AD域机器如何指定时钟服务器,active-directory – 如何让我的域控制器与正确的外部时间源同步?...
- 洛谷 P3384 【模板】树链剖分
- 生成树协议实验报告_多生成树协议MSTP
- easyui的datagrid的使用方法
- 如何隐藏电脑下方工具栏个别图标_最酷!最帅!最拽!这就是你想要的样子!工具栏美化终极篇...
- 用域控制禁止本地存盘禁止使用移动磁盘以防止图纸泄密的解决方案
- Python入门教程丨1300多行代码,让你轻松掌握基础知识点
- vue init失败解决方案-终极版
- 顺序表的动态存储细节
- 关于值传递和指针传递
- [css]通过transform缩放邮件客户端h5页面
- 怎样搞研究的一套思路
- Scala对象 转Json字符串
- c4d r21中文语言包安装失败怎么办,Windows10系统下语言包安装失败的解决方案
- 权力的游戏中文字幕词云图
热门文章
- 第三十二课.脉冲神经网络SNN
- 1.4 微生物对人类社会的影响
- 223.主成分分析PCA
- 面对这些情况,要勇于说“不​”
- R语言ggplot2可视化堆叠的条形图(stacked bar plot)并在每一个条形图的的中间添加对应的数值、值标签定位在geom_col堆叠的条形图中的每个条形段的中间
- plotly基于dataframe数据绘制柱状图(bar plot)
- Error in plot.new(): figure margins too large
- java对文本文件进行操作:读取、修改、添加、删除、重命名等
- R创建分类变量(categorical variable)
- java+构建+工具+Ant+Maven+Gradle