LeetCode 目录
Leetcode 54:螺旋矩阵Ⅰ
Leetcode 59:螺旋矩阵 Ⅱ
Leetcode 111: 二叉树的最小深度【递归/非递归求解/队列】
LeetCode 149 max-points-on-a-line
对于给定的n个位于同一二维平面上的点,求最多能有多少个点位于同一直线上
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
二重遍历循环,构建 斜率->点的数量 map
第一重循环遍历起始点x,第二重遍历剩余的点y
x,y重合,则经过x的所有直线点数dup+1;
x与y不重合,x与y斜率k的直线点数+1,期间考虑垂直的情况,垂直时k=0
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
class Solution {
public:
int maxPoints(vector<Point> &points) {
int size = points.size();
if(size == 0)
{
return 0;
}
else if(size == 1)
{
return 1;
}
int ans = 0;
for(int i = 0;i<size;i++)
{
int curmax = 1;
map<double,int>mp;
int vcnt = 0; //垂直点的个数
int dup = 0; //重复点的个数
for(int j = 0;j<size;j++)
{
if(j != i)
{
double x1 = points[i].x - points[j].x;
double y1 = points[i].y - points[j].y;
if(x1 == 0 && y1 == 0) //说明是重复点
{
dup++;
}
else if(x1==0) //垂直点
{
if(vcnt==0)
{
vcnt = 2;
}
else{ //说明之前该点已经统计过一次
vcnt++;
}
curmax = max(vcnt,curmax);
}
else
{
double k = y1/x1;
if(mp[k] == 0)
{
mp[k] = 2;
}
else{
mp[k]++;
}
curmax = max(mp[k],curmax);
}
}
}
ans = max(ans,dup+curmax);
}
return ans;
}
};
C++ map知识点
1 简介
map 是STL的一个关联容器,提供一对一的键值对 key-value对应
其中关键字key在map中只能出现一次
map可存储任意类型的数据,包括自定义的数据类型
内部使用红黑树,复杂度基本是lg(N)
2 使用
#include <map> //注意点:STL头文件没有扩展名.h
定义
map<int,string> stu
插入元素
stu.insert(pair<int,string>(666,"Me"));
stu.insert(map<int,sting>::value_type(666,"Me"))
stu[666] = "Me" //常用
寻找元素
//查找map中是否包含某个关键字条目用find()方法,传入的参数是要查找的key,不存在则返回map::end()的值
location = find("666")
string stu1 = stu[666]; //获得key=666对应的value值
删除元素
iterator erase(iterator it);//通过一个条目对象删除
iterator erase(iterator first,iterator last);//删除一个范围
size_type erase(const Key& key);//通过关键字删除
栗子
iter = mapStudent.find("666");
mapStudent.erase(iter); //迭代器删除
//用关键字刪除
int n = mapStudent.erase("123"); //如果刪除了会返回1,否則返回0
//用迭代器范围刪除 : 把整个map清空
mapStudent.erase(stu.begin(), stu.end());
//等同于mapStudent.clear()
其他基本操作
begin() 返回指向map头部的迭代器
end() 返回指向map末尾的迭代器
erase() 删除一个元素
find() 查找一个元素
clear() 删除所有元素
empty() 如果map为空则返回true
count() 返回指定元素出现的次数
size() 当前已经插入了多少数据,size函数,返回int
insert() 插入元素
swap() 交换两个map