Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)

问题:求数组中,所有和为0 的三个元素。

解题思路:

自己想了一个解法,但是扔上去超时了,然后在网上看到使用双指针的算法,理解后,把这道题解决了。

第一步,对数组排序。

第二步,

分析1:对于元素 S[i] , 最后的答案可以分为两种,包含 S[i] 的,和不包含 S[i] 的。当包含 S[i] 的情况都找到后,后续就可以不用在考虑 S[i] 。

对于 S[i] , l = i+1, r = len-1 。若 s[i] + S[l] + S[r] == 0, 则为原问题的一个解。

  • 当 S[i] + S[l] > -S[r] 时,则 r--
  • 当 S[i] + S[l] < -S[r] 时,则 l++
  • 当 S[i] + S[i] = -S[r] 时, 表示是原问题的一个解,则 l++, r--;

第三步,性能优化。同样根据分析1,若 S[i] == S[i+1],可以跳过。

vector<vector<int>> threeSum(vector<int>& nums) {

    vector<vector<int>> res;

    std::sort(nums.begin(), nums.end());

    map<string, vector<int>> key_res;

    for (int i =  ; i < (int)nums.size(); i++) {

        // star 剪枝优化
if (i >= ) {
while (nums[i] == nums[i-]) {
i++;
continue;
}
}
// end 剪枝优化 int l = i+;
int r = (int)nums.size()-; while (l < r) {
if (nums[l] + nums[r] > -nums[i]) {
r--;
continue;
}
else if (nums[l] + nums[r] < -nums[i]){
l++;
}else{
string k = to_string(nums[i]) + "," + to_string(nums[l]) + "," + to_string(nums[r]); vector<int> tmp = {nums[i], nums[l] , nums[r]};
key_res[k] = tmp; l++;
r--;
}
}
} map<string, vector<int>>::iterator m_iter;
for (m_iter = key_res.begin(); m_iter != key_res.end(); m_iter++) {
res.push_back(m_iter->second);
} return res;
}

[LeetCode] 3Sum 解题思路的更多相关文章

  1. leetcode array解题思路

    Array *532. K-diff Pairs in an Array 方案一:暴力搜索, N平方的时间复杂度,空间复杂度N 数组长度为10000,使用O(N平方)的解法担心TLE,不建议使用,尽管 ...

  2. leetcode每日解题思路 221 Maximal Square

    问题描述: 题目链接:221 Maximal Square 问题找解决的是给出一个M*N的矩阵, 只有'1', '0',两种元素: 需要你从中找出 由'1'组成的最大正方形.恩, 就是这样. 我们看到 ...

  3. leetcode BFS解题思路

    Word Ladder 思路一:单向bfs, 使用visited数组记录哪些已经访问过了, 访问过的就不允许再次入队, 同时这里想到的是使用26个英文字母,枚举可能的取值, 类似brute force ...

  4. [LeetCode] 16. 3Sum Closest 解题思路

    Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...

  5. [LeetCode] 76. Minimum Window Substring 解题思路

    Given a string S and a string T, find the minimum window in S which will contain all the characters ...

  6. [LeetCode] Minimum Size Subarray Sum 解题思路

    Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...

  7. [LeetCode] Word Break 解题思路

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

  8. [LeetCode] Longest Valid Parentheses 解题思路

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  9. [LeetCode] 134. Gas Station 解题思路

    There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...

随机推荐

  1. Google Web Designer 测试

    这东东完全就是一个flash啊,简单测试,感觉就是个做HTML5动画的..不过暂时是beta版的, 官方安装版的半天打不开,这边有个绿色版的,需要的童鞋可以这里下载:百度网盘

  2. wpf采用Xps实现文档显示、套打功能(原创)

    近期的一个项目需对数据进行套打,用户要求现场不允许安装office.页面预览显示必须要与文档完全一致,xps文档来对数据进行处理.Wpf的DocumentView 控件可以直接将数据进行显示,xps也 ...

  3. js异步脚本

    1.延迟脚本 HTML4.01为<script>标签定义了defer属性,为了表明脚本在执行时不会影响页面的构造.也就是说,脚本会在整个页面都解析完毕后再运行.因此在<script& ...

  4. python之全栈开发——————IO模型

    一:在讲IO模型之前我们首先来讲一下事件驱动模型,属于一种编程的范式,那么我们以前就是传统式编程,来看看有什么区别吧(此处为借鉴别人的) 传统的编程是如下线性模式的: 开始--->代码块A--- ...

  5. POJ 1035 Spell checker 简单字符串匹配

    在输入的单词中删除或替换或插入一个字符,看是否在字典中.直接暴力,172ms.. #include <stdio.h> #include <string.h> ]; ][], ...

  6. 使用ajax和history.pushState无刷新改变页面URL onpopstate(转)

    Javascript代码 var htmlData1 = $.ajax(    {    url: "/getXXXResponse",    async: false }).re ...

  7. 【ASP.NET】从服务器端注册客户端脚本

    一.在Asp.net 服务端处理脚本,一般都用 ClientScriptManager ,即web窗体服务端的this.ClientScript.该对象比较常用的方法: 1.RegisterArray ...

  8. CocoaPods安装和使用及问题:Setting up CocoaPods master repo-b

    目录 CocoaPods是什么? 如何下载和安装CocoaPods? 如何使用CocoaPods? 场景1:利用CocoaPods,在项目中导入AFNetworking类库 场景2:如何正确编译运行一 ...

  9. 获取ListControl控件中(复选框)CheckBox的状态

    原文地址:http://blog.chinaunix.net/uid-20680966-id-1896376.html 1 建立测试工程      新建一个对话框工程,并添加一个CListCtrl控件 ...

  10. 【POJ2406】 Power Strings (KMP)

    Power Strings Description Given two strings a and b we define a*b to be their concatenation. For exa ...