★ 算法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 };
    }
};
相关推荐
JieE21217 小时前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE21217 小时前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术1 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦1 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
clint4561 天前
C++进阶(1)——前景提要
c++
用户497863050731 天前
(一)小红的数组操作
算法·编程语言
夜悊1 天前
C++代码示例:进制数简单生成工具
c++
怕浪猫1 天前
Electron 系列文章封面图
算法·架构·前端框架
郝学胜_神的一滴1 天前
CMake 021: IF 条件判据详诠
c++·cmake