leetcode 确定同一直线上最多点数

/**
 * struct Point {
 *	int x;
 *	int y;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param points Point类vector 
     * @return int整型
     */
    int maxPoints(vector<Point>& points) {
        // write code here
        int p=points.size();
        if(p<=2)
            return p;
         int res=0;//用于比较的中间变量,为何要提前赋值为0????
        for(int i=0;i<p;i++)
        {
            int d=1;//重复的个数
            map<float,int> mp;
            for(int j=i+1;j<p;j++)
            {
                if(points[i].x==points[j].x)
                {
                    if(points[i].y==points[j].y)
                        d++;
                    else
                        mp[INT_MAX]++;
                }
                else
                {
                    float k=(points[j].y-points[i].y)*1.0/(points[j].x-points[i].x);
                    mp[k]++;
                }
            }
           for(auto i=mp.begin();i!=mp.end();i++)
           {
               res=max(res,i->second+d);
           }            
            
        }
        
        return res;
        
        
        
    }
};

关于map<float,int>mp:
C++关联式容器:map
map¶
map 是有序键值对(Attribute–value pair)容器,它的元素的键是唯一的。搜索、移除和插入操作拥有对数复杂度。 map 通常实现为红黑树。

你可能需要存储一些键值对,例如存储学生姓名对应的分数: Tom 0 , Bob 100 , Alan 100 。 但是由于数组下标只能为非负整数,所以无法用姓名作为下标来存储,这个时候最简单的办法就是使用 STL 中的 map 了!

map 重载了 operator[] ,可以用任意定义了 operator < 的类型作为下标(在 map 中叫做 key ,也就是索引):

map<Key, T> yourMap;
其中, Key 是键的类型, T 是值的类型,下面是使用 map 的实例:

map<string, int> mp;
添加元素¶
直接赋值,例如 mp[“Tom”]=0
通过插入一个类型为 pair<Key, T> 的值,例如 mp.insert(pair<string,int>(“Alan”,100));
使用 initializer_list :

map<string, int> mp = {{“Tom”, 0}, {“Bob”, “100”}, {“Alan”, 100}};
查找、修改元素
使用赋值语法: int grade=mp[“Tom”] 。
使用成员函数 iterator find( const Key& key ); 来确定一个索引是否在 map 中。它会返回指向该元素的迭代器;如果索引不在 map 中,则会返回尾后迭代器 mp.end() 。
如果你想获得 map 里全部的元素,请使用迭代器,解引用迭代器会得到一个类型为 pair<Key, T> 的值:

for (iter = mp.begin(); iter != mp.end(); ++iter)
  cout << iter->first << " " << iter->second << endl;

其中使用 mp.begin() 可以得到指向 map 首元素的迭代器。 如果使用 C++11(及以上),还可以使用 C++11 的范围 for 循环

for (auto &i : mp) {
  printf("Key : %d, Value : %d\n", i.first, i.second);
}

使用迭代器遍历大小为 的 map 的时间复杂度是 。

删除元素¶
如果你想删除 Tom 这个元素,则可以利用 find 函数找到 Tom ,然后再 erase 如下

map<string, int>::iterator it;
it = mp.find("Tom");
mp.erase(it)

如果你想清空所有的元素,可以直接 mp.clear()

其他函数¶

count 返回匹配特定键的元素出现的次数,例如 mp.count("Tom") 。
swap 可以交换两个 map ,例如 swap(m1,m2) 。
size 返回 map 中元素的个数。
empty 如果 map 为空则返回 true ,例如 mp.empty()

代码参考题解:
https://www.nowcoder.com/questionTerminal/bfc691e0100441cdb8ec153f32540be2?answerType=1&f=discussion

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值