当前位置:网站首页>两数之和、三数之和(排序+双指针)
两数之和、三数之和(排序+双指针)
2022-07-05 22:50:00 【BugMaker-shen】
一、和为s的两个数字
升序,使用双指针遍历即可
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int l = 0;
int r = nums.size() - 1;
while(l < r){
if(nums[l] + nums[r] == target){
return {
nums[l], nums[r]};
}else if(nums[l] + nums[r] > target){
r--;
}else{
l++;
}
}
return {
};
}
};
二、两数之和
用和哈希表存储已经遍历过且没找到和为target的数,key为值,value为元素下标
用target减去当前遍历的数,在哈希表中查找,查找到就可以返回当前下标(i)和从哈希表取出的下标(target - nums[i])。没找到就在哈希表保存当前元素值以及下标
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> mp; // mp[val] = index
for(int i = 0; i < nums.size(); i++){
if (mp.find(target - nums[i]) != mp.end()){
return {
i, mp[target - nums[i]]};
}else{
mp[nums[i]] = i;
}
}
return {
};
}
};
三、三数之和
用排序+双指针的方法,时间复杂度为 O ( N 2 ) O(N^2) O(N2)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end(), less<int>());
set<vector<int>> ans;
for(int l = 0; l < (int)nums.size() - 2 && nums[l] <= 0; l++){
int mid = l + 1;
int r = nums.size() - 1;
while(mid < r){
int sum = nums[l] + nums[mid] + nums[r];
if(sum == 0){
ans.insert({
nums[l], nums[mid], nums[r]});
r--;
while (mid < r && nums[r] == nums[r + 1]) r--; // while循环用于去重
mid++;
while (mid < r && nums[mid] == nums[mid - 1]) mid++; // while循环用于去重
}else if(sum > 0){
r--;
while (mid < r && nums[r] == nums[r + 1]) r--; // while循环用于去重
}else{
mid++;
while (mid < r && nums[mid] == nums[mid - 1]) mid++; // while循环用于去重
}
}
}
return vector<vector<int>> (ans.begin(), ans.end());
}
};
四、最接近的三数之和
未排序,直接暴力回溯,超时
class Solution {
public:
vector<int> choice;
int gap = INT_MAX;
int target_;
int ans;
void func(int i, const vector<int>& nums){
if(choice.size() == 3){
int sum = accumulate(choice.begin(), choice.end(), 0);
if (abs(target_ - sum) < gap) {
ans = sum;
gap = abs(target_ - sum);
}
}else{
for(int j = i; j < nums.size(); j++){
choice.push_back(nums[j]);
func(j + 1, nums);
choice.pop_back();
}
}
}
int threeSumClosest(vector<int>& nums, int target) {
target_ = target;
func(0, nums);
return ans;
}
};
排序+双指针
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end(), less<int>());
long ans = INT_MAX;
for(int l = 0; l < (int)nums.size() - 2; l++){
int mid = l + 1;
int r = nums.size() - 1;
while(mid < r){
int sum = nums[l] + nums[mid] + nums[r];
if(abs(sum - target) < abs(ans - target)){
// sum和target的距离减小,则更新ans
ans = sum;
}
if(sum == target){
// 和为target,则距离target最近,为0,返回当前sum
return sum;
}else if(sum > target){
r--;
}else{
mid++;
}
}
}
return ans;
}
};
边栏推荐
- Getting started stm32--gpio (running lantern) (nanny level)
- 一文搞定class的微观结构和指令
- Global and Chinese market of water treatment technology 2022-2028: Research Report on technology, participants, trends, market size and share
- Matlab smooth curve connection scatter diagram
- Tensor attribute statistics
- 终于搞懂什么是动态规划的
- The countdown to the launch of metaverse ape is hot
- 基于STM32的ADC采样序列频谱分析
- Un article traite de la microstructure et des instructions de la classe
- 解决thinkphp启动时“No input file specified”的问题
猜你喜欢
谷歌地图案例
【Note17】PECI(Platform Environment Control Interface)
Lesson 1: serpentine matrix
30 optimization skills about mysql, super practical
Exponential weighted average and its deviation elimination
The method and principle of viewing the last modification time of the web page
Post-90s tester: "after joining Ali, this time, I decided not to change jobs."
Distributed resource management and task scheduling framework yarn
[untitled]
Editor extensions in unity
随机推荐
How can easycvr cluster deployment solve the massive video access and concurrency requirements in the project?
【无标题】
Composition of interface
解决thinkphp启动时“No input file specified”的问题
I closed the open source project alinesno cloud service
Common model making instructions
PLC编程基础之数据类型、变量声明、全局变量和I/O映射(CODESYS篇 )
MoCo: Momentum Contrast for Unsupervised Visual Representation Learning
audiopolicy
南京:全面启用商品房买卖电子合同
openresty ngx_lua正则表达式
从 1.5 开始搭建一个微服务框架——日志追踪 traceId
Vcomp110.dll download -vcomp110 What if DLL is lost
d3dx9_ How to repair 31.dll_ d3dx9_ 31. Solution to missing DLL
Hcip day 11 (BGP agreement)
TOPSIS code part of good and bad solution distance method
The countdown to the launch of metaverse ape is hot
d3dx9_ What if 29.dll is missing? System missing d3dx9_ Solution of 29.dll file
30 optimization skills about mysql, super practical
Getting started stm32--gpio (running lantern) (nanny level)