★ 算法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 };
    }
};
相关推荐
AI科技星2 分钟前
数术工坊 · 第四卷 橡皮泥江湖(拓扑学)【完整定稿】
c语言·开发语言·汇编·electron·概率论·拓扑学
张忠琳9 分钟前
【Go 1.26.4】Golang Select 深度解析
开发语言·后端·golang
AC赳赳老秦2 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源
大数据·开发语言·python·serverless·excel·deepseek·openclaw
提笔了无痕2 小时前
如何用Go实现整套RAG流程
开发语言·后端·golang
(Charon)2 小时前
【C++ 面试高频基础:指针、引用、const、static、new/delete 总结】
java·开发语言
一只齐刘海的猫2 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏1112 小时前
数据结构 | 八大排序
数据结构·算法·排序算法
2601_961875242 小时前
法考考试时间安排及科目|时间表|资料已整理
开发语言·c#·inverted-index·suffix-tree·sstable·r-tree·lsm-tree
AI科技星2 小时前
数术工坊第八卷:算力革命
c语言·开发语言·网络·量子计算·agi
Frank学习路上2 小时前
【C++】面试:关键字与语法特性
c++·面试