★ 算法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 };
    }
};
相关推荐
余俊晖10 分钟前
多模态大模型细粒度视觉理解:Vision-OPD在线策略自蒸馏技术方案概述
人工智能·深度学习·算法·多模态·opd
胖大和尚21 分钟前
在C++的类中,是否可以把函数声明成__device__
c++·cuda
-dzk-22 分钟前
【链表】LC 160.相交链表
数据结构·链表
脚踏实地皮皮晨25 分钟前
003003001_Grid控件
开发语言·windows·算法·c#·visual studio
十年磨剑走天涯28 分钟前
C++ STL 容器操作复杂度速查表
开发语言·c++
always_TT35 分钟前
【Python requirements.txt 依赖管理】
开发语言·python
Hi李耶37 分钟前
【LeetCode】6-Z字形变换
算法·leetcode·职场和发展
ziguo112238 分钟前
Windows API MessageBox 函数详解
c语言·c++·windows·visualstudio
王老师青少年编程42 分钟前
2023年CSP-J初赛真题及答案解析(11-15)
c++·真题·csp-j·答案·csp·初赛·信奥赛
15Moonlight44 分钟前
C++进阶(09):特殊类设计
开发语言·c++