题目:

1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

15.3Sum:

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.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

18. 4Sum

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

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

思路:

  这三道题本质上属于同一问题:给定一个数组和目标target,求k个元素,使得k个元素相加的和为target。可能出现的变式为:1.求元素的下标;2.不得重复使用同一元素等,下面进行分析。

  对于2Sum而言,要求a+b=target,也就是任意选定元素a,寻找数组中是否有元素b使得b=target-a。可以选择方法有:

    方法一:枚举所有的2-subset, 那么这样的复杂度就是从N选出2个,复杂度是O(N^2)

    方法二:对数组进行排序并利用头尾两个指针找到两个数使得他们的和等于target。

  对于3Sum而言,要求a+b+c=target,这道题可以转化为2Sum问题。即任意选定元素a,在剩余的元素中查找是否存在2个数使得b+c=targe-a。

  对于4Sum而言,也可以转化为2Sum问题。任意选定元素a和b,在剩余的元素中查找是否存在2个数使得c+d=targe-a-b。

 

代码:

2Sum:

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int l = ;
int r = nums.size() - ;
int i = ;
vector<int> result;
multimap<int, int> m;
multimap<int, int>::iterator itmulti;
for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++) {
int temp = *it;
m.insert(make_pair(temp, i++));
}
sort(nums.begin(), nums.end());
while (l < r) {
if (nums[l] + nums[r] == target) {
if (nums[l] == nums[r]) {
for (itmulti = m.equal_range(nums[l]).first;
itmulti != m.equal_range(nums[l]).second;
itmulti++) {
result.push_back((*itmulti).second);
}
} else {
itmulti = m.equal_range(nums[l]).first;
result.push_back((*itmulti).second);
itmulti = m.equal_range(nums[r]).first;
result.push_back((*itmulti).second);
}
break;
} else if (nums[l] + nums[r] < target) {
l++;
} else {
r--;
}
}
return result;
}
};

3Sum:

 class Solution {
public:
vector<vector<int> > threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int> > results;
for (int i = ; i < (signed) nums.size() - ; i++) {
if (i > && nums[i] == nums[i - ])
continue; int l = i + ;
int r = nums.size() - ;
while (l < r) {
if (nums[l] + nums[r] + nums[i] < ) {
l++;
} else if (nums[l] + nums[r] + nums[i] > ) {
r--;
} else {
vector<int> result;
result.push_back(nums[i]);
result.push_back(nums[l]);
result.push_back(nums[r]);
results.push_back(result);
while (l < r && nums[l] == nums[l + ]) {
l++;
}
while (l < r && nums[r] == nums[r - ]) {
r--;
}
l++;
r--;
}
}
}
return results;
}
};

4Sum:

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int l = ;
int r = nums.size() - ;
int i = ;
vector<int> result;
multimap<int, int> m;
multimap<int, int>::iterator itmulti;
for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++) {
int temp = *it;
m.insert(make_pair(temp, i++));
}
sort(nums.begin(), nums.end());
while (l < r) {
if (nums[l] + nums[r] == target) {
if (nums[l] == nums[r]) {
for (itmulti = m.equal_range(nums[l]).first;
itmulti != m.equal_range(nums[l]).second;
itmulti++) {
result.push_back((*itmulti).second);
}
} else {
itmulti = m.equal_range(nums[l]).first;
result.push_back((*itmulti).second);
itmulti = m.equal_range(nums[r]).first;
result.push_back((*itmulti).second);
}
break;
} else if (nums[l] + nums[r] < target) {
l++;
} else {
r--;
}
}
return result;
}
};

1. Two Sum&&15. 3Sum&&18. 4Sum的更多相关文章

  1. leetcode 1.Two Sum 、167. Two Sum II - Input array is sorted 、15. 3Sum 、16. 3Sum Closest 、 18. 4Sum 、653. Two Sum IV - Input is a BST

    1.two sum 用hash来存储数值和对应的位置索引,通过target-当前值来获得需要的值,然后再hash中寻找 错误代码1: Input:[3,2,4]6Output:[0,0]Expecte ...

  2. 15. 3Sum、16. 3Sum Closest和18. 4Sum

    15 3sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = ...

  3. LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum

    n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...

  4. [LeetCode] 18. 4Sum 四数之和

    Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...

  5. [LeetCode] 15. 3Sum 三数之和

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  6. 【LeetCode】18. 4Sum 四数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:four sum, 4sum, 四数之和,题解,leet ...

  7. [LeetCode][Python]18: 4Sum

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 18: 4Sumhttps://oj.leetcode.com/problem ...

  8. leetcode 15. 3Sum 二维vector

    传送门 15. 3Sum My Submissions Question Total Accepted: 108534 Total Submissions: 584814 Difficulty: Me ...

  9. LeetCode 15 3Sum [sort] <c++>

    LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...

随机推荐

  1. SPOJ Distinct Substrings SA

    正解:SA 解题报告: 传送门! 啊先给个翻译趴QwQ大概就是说给个字符串,求互不相等的子串的个数 算是道小水题辣趴,,,并不难想到的呢QAQ只是因为是新知识所以巩固下而已QAQ 然后就显然考虑合法方 ...

  2. Java并发问题--乐观锁与悲观锁以及乐观锁的一种实现方式-CAS

    首先介绍一些乐观锁与悲观锁: 悲观锁:总是假设最坏的情况,每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会阻塞直到它拿到锁.传统的关系型数据库里边就用到了很 ...

  3. oracle 日期取 月 日

    今天碰到只要取月份和天数,如果月份前面有0要去掉0.比如说2010-01-08 ,需要的结果是1-8. 引出了一系列的sql语句 第一: 利用to_number的函数转换自动截0 select to_ ...

  4. node (02 CommonJs 和 Nodejs 中自定义模块)顺便讲讲module.exports和exports的区别 dependencies 与 devDependencies 之间的区别

    CommonJS 规范的提出,主要是为了弥补当前 JavaScript 没有标准的缺陷.它的终极目标就是:提供一个类似 Python,Ruby 和 Java 语言的标准库,而不只是停留在小脚本程序的阶 ...

  5. One VS Rest

    简单来说就是分类的类别有多个,不再是二分,比如根据某些特征,什么温度.湿度.空气流动情况来预测天气,天气的label不能说是好天气和坏天气两种,而是分晴天.雨天.阴天,雪天等等,对于决策树或者从计算机 ...

  6. CentOS 7 系统优化

    系统调优4大子系统 1:找出系统中使用CPU最多的进程 2:找出系统中使用内存最多的进程 3:找出系统中对磁盘读写最多的进程 4:找出系统中使用网络最多的进程 系统调优概述 系统的运行状况:  CPU ...

  7. GDscript风格指南

    (惯例感谢godot开发组~~·) 缩进 缩进类型:Tabs (编辑器默认) 缩进大小:4 (编辑器默认) 每个缩进级别必须大于包含它的代码块. 良好的: for i in range(10): pr ...

  8. Restful API接口调用的方法总结

    restful 接口调用的方法 https://www.cnblogs.com/taozhiye/p/6704659.html http://www.jb51.net/article/120589.h ...

  9. django开发(一)

    django基础 1.django配置模块的各文件作用 一般来说标红的文件是需要我们具体配置和修改等的文件 2.django项目和功能编写的步骤 注:上面是功能模块,下面是配置模块.配置和功能解耦分离 ...

  10. Template模板

     目标 模板介绍 模板变量 常用标签 常用过滤器 自定义过滤器 模板结构 加载静态文件 一 模板介绍 在之前的章节中,视图函数只是直接返回文本,而在实际生产环境中其实很少这样用,因为实际的页面大多是带 ...