• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Max Points on a Line

斜率问题

 1 /**
 2  * Definition for a point.
 3  * struct Point {
 4  *     int x;
 5  *     int y;
 6  *     Point() : x(0), y(0) {}
 7  *     Point(int a, int b) : x(a), y(b) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxPoints(vector<Point> &points) {
13         map<double, int> S;
14         if (points.size() == 0) return 0;
15         int ans = 1;
16         for (int i = 0; i < points.size()-1; i++) {
17             int num = 1;
18             int samep = 0;
19             S.clear();
20             for (int j = i+1; j < points.size(); j++) {
21                 double k = numeric_limits<double>::infinity();
22                 if (points[j].x != points[i].x) k = (double)1.0*(points[j].y-points[i].y)/(points[j].x-points[i].x);
23                 else if (points[j].y == points[i].y) {samep++; continue;}
24                 if (S.count(k)) S[k]++;
25                 else S[k] = 2;
26                 num = max(num, S[k]);
27             }
28             ans = max(ans, num+samep);
29         }
30         return ans;
31     }
32 };

 C#

 1 /**
 2  * Definition for a point.
 3  * public class Point {
 4  *     public int x;
 5  *     public int y;
 6  *     public Point() { x = 0; y = 0; }
 7  *     public Point(int a, int b) { x = a; y = b; }
 8  * }
 9  */
10 public class Solution {
11     public int MaxPoints(Point[] points) {
12         Dictionary<double, int> S = new Dictionary<double, int>();
13         if (points.Length == 0) return 0;
14         int ans = 1;
15         for (int i = 0; i < points.Length-1; i++) {
16             int num = 1;
17             int samep = 0;
18             S = new Dictionary<double, int>();
19             for (int j = i+1; j < points.Length; j++) {
20                 double k = double.PositiveInfinity;
21                 if (points[j].x != points[i].x) k = (double)1.0*(points[j].y-points[i].y)/(points[j].x-points[i].x);
22                 else if (points[j].y == points[i].y) {
23                     samep++;
24                     continue;
25                 }
26                 if (S.ContainsKey(k)) S[k]++;
27                 else S.Add(k, 2);
28                 num = Math.Max(num, S[k]);
29             }
30             ans = Math.Max(ans, num + samep);
31         }
32         return ans;
33     }
34 }
View Code

 

posted @ 2014-01-09 07:59  ying_vincent  阅读(168)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3