1. Two Sum&&15. 3Sum&&18. 4Sum
题目:
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 a, b, c 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 a, b, c, 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的更多相关文章
- 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 ...
- 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 = ...
- LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum
n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...
- [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 ...
- [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 ...
- 【LeetCode】18. 4Sum 四数之和
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:four sum, 4sum, 四数之和,题解,leet ...
- [LeetCode][Python]18: 4Sum
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 18: 4Sumhttps://oj.leetcode.com/problem ...
- leetcode 15. 3Sum 二维vector
传送门 15. 3Sum My Submissions Question Total Accepted: 108534 Total Submissions: 584814 Difficulty: Me ...
- LeetCode 15 3Sum [sort] <c++>
LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...
随机推荐
- DBMS_METADATA.set_transform_param格式化输出
DBMS_METADATA.set_transform_param格式化输出获得DDL --输出信息采用缩排或换行格式化 EXEC DBMS_METADATA.set_transform_param( ...
- 斑马打印机ZT410中文打印
^XA ^CW1, E:SIMSUN.TTF^CI28^FO50,50^A1N,50,50^FD汉字^FS^XZ ******************************************* ...
- 分布式异步任务Celery
-A代表APP celery -A tasks worker --loglevel=info -n nodemaster -------------- celery@nodemaster v4.1.0 ...
- 函数作用域之闭包与this!
函数基础友情链接:http://speakingjs.com/es5/ch01.html#_functions 作用域链图解 var x = 1; function foo(){ var ...
- Bukkit之yaml动态读取
在使用bukkit框架写插件的时候会经常使用到yml格式的文件来存储配置或者玩家数据,这里来说一下实现yml中数据的动态读写: 先来看一下yml文件中的内容结构 public boolean addB ...
- Linux文件系统的硬连接和软连接
title: Linux文件系统的硬连接和软连接 date: 2018-02-06T20:26:25+08:00 tags: ["文件系统"] categories: [" ...
- MTCNN试用
检测工作想借用MTCNN里的48-net,源码来自CongWeilin Git 下下来就能跑,真是良心 进入pepare_data准备好数据以后进入48-net,目录下有一个pythonLayer.p ...
- Axis2开发WebService客户端 的3种方式
Axis2开发WebService客户端 的3种方式 在dos命令下 wsdl2java -uri wsdl的地址(网络上或者本地) -p com.whir.ezoffi ...
- c#查找窗口的两种办法
原文最早发表于百度空间2009-06-17 1.process.MainWindowTitle(这个只能获取一部分窗口)2.EnumWindows(用windows API)
- Java中static的用法解析
知识点1.static关键字a.可以修饰变量,方法,代码块b.修饰的变量和方法可以使用类名.变量名/类名.方法名调用c.static修饰的资源为静态资源,在类加载的时候执行d.在静态方法中只能调用静态 ...