LeetCode15.三数之和 JavaScript
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
] 答案参考:
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
var result = new Array();
var len = nums.length;
var flag = 0;
var hash = {};
nums.sort((a, b) => {
return a-b;
});
if(nums[0] > 0 || nums[len - 1] < 0) return result;
for(var i = 0; i < len; i++){
if(nums[i] === nums[i-1]) continue;
flag = 0 - nums[i];
var start = i + 1, end = len - 1;
while(start < end){
var middle = new Array();
if(nums[start] + nums[end] < flag){
start ++;
} else if(nums[start] + nums[end] > flag){
end--;
} else {
middle.push(nums[i]);
middle.push(nums[start]);
middle.push(nums[end]);
if(!hash[middle]){
hash[middle] = true;
result.push(middle);
}
start += 1;
end -= 1;
while(start < end && nums[start] === nums[start - 1]){
start += 1;
}
while(start < end && nums[end] === nums[end + 1]){
end -= 1;
}
}
}
}
return result; };
LeetCode15.三数之和 JavaScript的更多相关文章
- Leetcode13. 罗马数字转整数Leetcode14. 最长公共前缀Leetcode15. 三数之和Leetcode16. 最接近的三数之和Leetcode17. 电话号码的字母组合
> 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数  先处理特殊情况,然后 先排序 注意不重复,只需要有 ...
- 南大算法设计与分析课程OJ答案代码(4)--变位词、三数之和
问题 A: 变位词 时间限制: 2 Sec 内存限制: 10 MB提交: 322 解决: 59提交 状态 算法问答 题目描述 请大家在做oj题之前,仔细阅读关于抄袭的说明http://www.bi ...
- LeetCode 15. 三数之和(3Sum)
15. 三数之和 15. 3Sum 题目描述 Given an array nums of n integers, are there elements a, b, c in nums such th ...
- [LeetCode] 3Sum Smaller 三数之和较小值
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...
随机推荐
- PCU
PCU(Peak concurrent users ),互联网术语,应用在网络游戏和其他互联网服务领域,意思是最高同时在线人数 业务系统架构性能提升主要分为两种不同的方式,scale-out(横向扩展 ...
- jquery中Ajax提交配合PHP使用的注意事项-编码
问题:Ajax提交的数据的编码为utf-8,并且返回的数据也要求是utf-8的,如果说你的系统不是utf-8编码的话,那会让你痛不欲生! 解决方法:(比较笨拙的方法,但是很好用) 对于接收的数据,使用 ...
- FreeSwitch无法启动,提示进程pid锁定的解决方法
来源:https://stackoverflow.com/questions/12817232/how-do-i-call-a-local-softphone-on-freeswitch error ...
- Android-自定义View实现ImageView播放gif
http://blog.csdn.net/guolin_blog/article/details/11100315 总体思路是这样的 PowerImageView类继承ImageView类 给Powe ...
- js实现手风琴效果
之前在慕课网上有练习手风琴效果,但是老师使用jquery简简单单的两三行实现了,今天自己用js练习一下效果 <div id="divbox"> <ul> & ...
- 关于i 标签盛放背景图像
1.html部分 <div class="hover right"> <i class="log_change state_psd">& ...
- vuejs的双向数据绑定实现原理——object.defineproperty()
视图和数据变化绑定 而vue.js主要利用了accessor descriptors的set和get来更新视图,这里看到的这个例子挺好,是一个简单的绑定.对于一个html页面 <div> ...
- Mac系统在finder拦显示当前所浏览的文件路径的方法
我们在使用MAC时,Finder栏默认只显示当前浏览的文件夹名称,而没有显示访问路径,这个问题该怎么解决呢? 编辑node的时候需要路径,亲测有效啦~可以试下! 操作步骤: 打开“终端”(应用程序-& ...
- tdf sample
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net ...
- Ajax 重构的步骤
Ajax重构大致可以分为以下3三个步骤. 一 创建一个单独的JS文件,名称为AjaxRequest.js,并且在该文件中编写重构Ajax 所需的代码具体代码如下:var net = new Objec ...