当前位置:网站首页>leetcode-2280:表示一个折线图的最少线段数
leetcode-2280:表示一个折线图的最少线段数
2022-07-02 23:55:00 【菊头蝙蝠】
leetcode-2280:表示一个折线图的最少线段数
题目
给你一个二维整数数组 stockPrices ,其中 stockPrices[i] = [dayi, pricei] 表示股票在 dayi 的价格为 pricei 。折线图 是一个二维平面上的若干个点组成的图,横坐标表示日期,纵坐标表示价格,折线图由相邻的点连接而成。比方说下图是一个例子:

请你返回要表示一个折线图所需要的 最少线段数 。
示例 1:
输入:stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]
输出:3
解释:
上图为输入对应的图,横坐标表示日期,纵坐标表示价格。
以下 3 个线段可以表示折线图:
- 线段 1 (红色)从 (1,7) 到 (4,4) ,经过 (1,7) ,(2,6) ,(3,5) 和 (4,4) 。
- 线段 2 (蓝色)从 (4,4) 到 (5,4) 。
- 线段 3 (绿色)从 (5,4) 到 (8,1) ,经过 (5,4) ,(6,3) ,(7,2) 和 (8,1) 。
可以证明,无法用少于 3 条线段表示这个折线图。
示例 2:
输入:stockPrices = [[3,4],[1,2],[7,8],[2,3]]
输出:1
解释:
如上图所示,折线图可以用一条线段表示。
解题
方法一:判断斜率相等(转化成乘法)
将除法a[0]/b[0]==a[1]/b[1]转化为乘法,就可以避免精度问题,四舍五入。很有可能两个不同的斜率,但是四舍五入成相等了。
这道题其实就是计算这个折线有多少种斜率
(注意转换为乘法会溢出,因此要用uint64_t)
class Solution {
public:
bool compareVec(vector<int>& a,vector<int>& b){
return (uint64_t)a[0]*b[1]==(uint64_t)a[1]*b[0];
}
int minimumLines(vector<vector<int>>& stockPrices) {
int n=stockPrices.size();
vector<int> pre;
int count=0;
sort(stockPrices.begin(),stockPrices.end(),[](vector<int>&a,vector<int>&b){
return a[0]<b[0];
});
for(int i=1;i<n;i++){
vector<int> vec={
stockPrices[i][0]-stockPrices[i-1][0],stockPrices[i][1]-stockPrices[i-1][1]};
if(i==1) count=1;
else{
if(compareVec(pre,vec)) continue;
else count++;
}
pre=vec;
}
return count;
}
};
边栏推荐
- 奥斯陆大学:Li Meng | 基于Swin-Transformer的深度强化学习
- NC24325 [USACO 2012 Mar S]Flowerpot
- Is there a free text to speech tool to help recommend?
- NC20806 区区区间间间
- Array common operation methods sorting (including ES6) and detailed use
- Automated defect analysis in electronic microscopic images
- Free we media essential tools sharing
- Teach you JDBC hand in hand -- structure separation
- Vulkan-实践第一弹
- 详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
猜你喜欢

Teach you JDBC hand in hand -- structure separation

字符设备注册常用的两种方法和步骤

Use Jenkins II job

Sentry developer contribution Guide - configure pycharm

【AutoSAR 十三 NVM】

Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径

Logback configuration file

Linux Software: how to install redis service

AEM: Nanlin fan Ben et al. - plant rhizosphere growth promoting bacteria control soybean blight

利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度
随机推荐
Use Jenkins II job
为什么网站打开速度慢?
ftrace工具的介绍及使用
百度智能云牵头打造智能云综合标准化平台
Automated defect analysis in electron microscopic images-论文阅读笔记
How to find out the currently running version of Solr- How do I find out version of currently running Solr?
Some introduction and precautions about XML
1.11 - bus
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
Helm basic learning
Linux软件:如何安装Redis服务
NC24840 [USACO 2009 Mar S]Look Up
毕业总结
Program analysis and Optimization - 9 appendix XLA buffer assignment
Vulkan-实践第一弹
Vulkan-性能及精细化
字符设备注册常用的两种方法和步骤
百数不断创新,打造自由的低代码办公工具
Linux Software: how to install redis service
2022中国3D视觉企业(引导定位、分拣场景)厂商名单