★ 算法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 };
    }
};
相关推荐
qetfw1 天前
Bash 基础:脚本执行、引号与命令替换验证
linux·开发语言·chrome·bash
杜 硕1 天前
从零开始的C++生活——第四讲
开发语言·c++·生活
云和数据.ChenGuang1 天前
Python 集合(set)常用函数详解与实战案例
开发语言·python·深度学习·langchain
文丑颜不良啊1 天前
LeetCode576~600题目解析
java·leetcode
隔窗听雨眠1 天前
从PHP2Shell回望:PHP内核漏洞的二十年演进与AI时代的攻防转折
开发语言·人工智能·php
lisw051 天前
分岔论揭示演化突变密码
开发语言·算法·数学建模
hunteritself1 天前
AI 挖出 PHP「致命漏洞」!欧洲政府连夜关站,日本首相紧急喊话
开发语言·人工智能·php
aqiu1111111 天前
C++ TopK:使用 nth_element 快速求最小 K 个数(蓝桥杯 / LeetCode 可用)
算法
H.莓飛1 天前
【数据结构】快速排序专题
linux·服务器·c语言·数据结构·visual studio
努力实干1 天前
Qt/C++ 模块化设计与工程组织
开发语言·c++·qt