★ 算法OJ题 ★ 力扣 LCR179 - 和为 s 的两个数字

Ciallo~(∠・ω< )⌒☆ ~ 今天,小诗歌剧将和大家一起做一道双指针算法题--和为 s 的两个数字~

目录

[一 题目](#一 题目)

[二 算法解析](#二 算法解析)

[三 编写算法](#三 编写算法)


一 题目

LCR 179. 查找总价格为目标值的两个商品 - 力扣(LeetCode)

二 算法解析

解法⼀:暴力解法 O(N ^ 2)

算法思路: 两层 for 循环列出所有两个数字的组合,判断是否等于⽬标值。(会超时)

cpp 复制代码
class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) 
	{
		int n = nums.size();
		for (int i = 0; i < n; i++) // 第⼀层循环从前往后列举第⼀个数
		{ 
			for (int j = i + 1; j < n; j++) // 第⼆层循环从 i 位置之后列举第⼆个数
			{ 
				if (nums[i] + nums[j] == target) // 两个数的和等于⽬标值,说明我们已经找到结果了
					return { nums[i], nums[j] };
			}
		}
		return { -1, -1 };
	}
};

解法⼆:利用单调性,使用双指针 - 对撞指针解决问题

算法思路: 注意到本题是升序的数组 ,因此可以⽤对撞指针优化时间复杂度

三 编写算法

cpp 复制代码
class Solution {
public:
    vector<int> twoSum(vector<int>& price, int target) 
    {
        int left = 0, right = price.size() - 1;
        while(left < right)
        {
            int sum =  price[left] + price[right];
            if(sum == target)
                return {price[left], price[right]};
            if(sum < target)
                left++;
            if(sum > target)
                right--;
        }
        return { -1, -1 };
    }
};
相关推荐
benchmark_cc8 小时前
如何用 Python + QuantDash 快速构建高胜率“配对交易(Pairs Trading)”策略?
开发语言·人工智能·python·pandas·量化交易·quantdash
renhongxia19 小时前
世界模型,是“空中楼阁”还是AGI的“最后一块拼图”?
运维·服务器·数据库·人工智能·算法·agi
程序员无隅10 小时前
Coding Agent 为什么压缩上下文后还能继续工作?上下文模块设计拆解
java·开发语言·数据库
Python+9910 小时前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
G.O.G.O.G10 小时前
LeetCode SQL 从入门到精通(MySQL)06(上)
数据库·sql·mysql·leetcode
二炮手亮子10 小时前
浅记java线程池
java·开发语言
zmzb010311 小时前
C++课后习题训练记录Day157
开发语言·c++
dunge202611 小时前
2026年7月最新ChatGPT Plus / Pro 与 Codex:当 AI Agent 最新5.6版本来袭,必须理解事务、幂等与补偿
开发语言·人工智能·python
zephyr0512 小时前
动态规划-最长上升子序列问题
算法·动态规划
闪电悠米12 小时前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法