如何获取哈希键?

时间:2018-11-13 13:39:54

标签: hash

当我在leetcode上解决此问题(149. Max Points on a Line)时,遇到此情况时它有一个错误:

Input [[0,0],[94911151,94911150],[94911152,94911151]]
Output 3
Expected 2

这是我的代码:

/**
 * 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();
        int ans = 0;
        if (size == 0) return 0;
        unordered_map<double, int> mp;
        double k;
        for (int i = 0; i < size; ++i) {
            int num = 0;
            for (int j = i + 1; j < size; ++j) {
                if (points[i].x == points[j].x && points[i].y == points[j].y) {
                    num++;
                    continue;
                }
                // my question in below code.
                // how can I get the hash key according to slope
                if (points[j].x - points[i].x != 0)
                    k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);  // calculate the slope.
                else k = INT_MAX;
                mp[k]++;
            }
            if (mp[k] == 0) mp[k] = 1, num--;
            for (auto it = mp.begin(); it != mp.end(); ++it) {
                if (it->second > ans) {
                    ans = it->second;
                    ans += num;
                }    
            }
            mp.clear();
        }
        return ans+1;
    }
};

在上述测试案例中,当它使用[0,0][94911151,94911150]计算斜率时,它会返回k = 1。所以我想知道如何获取正确的哈希键来解决此问题?

0 个答案:

没有答案