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 ...
随机推荐
- MySQL5.7 虚拟列实现表达式或函数索引
MySQL5.7 虚拟列实现表达式或函数索引 http://www.linuxidc.com/Linux/2015-11/125162.htm https://dev.mysql.com/doc/re ...
- java框架之SpringBoot(12)-消息及整合RabbitMQ
前言 概述 大多数应用中,可通过消息服务中间件来提升系统异步通信.扩展解耦的能力. 消息服务中两个重要概念:消息代理(message broker)和目的地(destination).当消息发送者发送 ...
- python基础之 列表,元组,字典
other help(str.strip) #查看是否有返回值以及返回值类型[] :称为索引操作符 1.列表 列表相比字符串来说能存储大量数据的python的基本数据类型,并且也拥有字符串的一些方法( ...
- 160A
#include <stdio.h> int main() { int n; int sum1=0, sum2=0, sum3=0; int x, y, z; scanf("%d ...
- C# Newtonsoft.Json JsonSerializerSettings 全局序列化设置
Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings(); JsonC ...
- 为什么入门首选C语言
对于大部分程序员,C语言是学习编程的第一门语言,很少有不了解C的程序员. C语言除了能让你了解编程的相关概念,带你走进编程的大门,还能让你明白程序的运行原理,比如,计算机的各个部件是如何交互的,程序在 ...
- for loop
https://www.cnblogs.com/EasonJim/p/8315939.html
- 14 python读取文件时出现UnicodeDecodeError: 'gbk' codec can't decode byte 0xb7 in position 26: illegal multibyte sequence解决方法
>>> f = open("D:\\all.txt", "r")>>> f.read()Traceback (most re ...
- 使用fastdfs搭建文件服务器
一:安装tracker 1. 拷贝安装目录下各个.gz文件到/usr/local/src下,解压各个install lib,例如tar zxvf xxx.tar.gz 2. 先安装libfastcom ...
- 复习-css元素定位
css元素定位 <style type="text/css"> body{ margin: 15px; font-family: "Adobe 宋体 Std ...