您的位置:首页 > 其它

Leetcode之 Max Points on a Line

2014-09-08 23:49 477 查看
这道题是Leetcode里面AC率最低的题目。其实理解好题目要做这道题是完全没有问题的。

首先我们先看看题目:

Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.

其实这道题的意思是:

给你一组点,求共线最多点的个数。

分析:

任意一条直线都可以表述为

y = ax + b

假设,有两个点(x1,y1), (x2,y2),如果他们都在这条直线上则有

y1 = kx1 +b

y2 = kx2 +b

由此可以得到关系,k = (y2-y1)/(x2-x1)。

b=y1-kx1

即如果点c和点a的斜率为k,

而点b和点a的斜率也为k,可以知道点c和点b也在一条线上。

取定一个点points[i], 遍历其他所有节点, 然后统计斜率相同的点数,并求取最大值即可。

基本结题思路是:

for循环两次,然后求出两个点组成的一条直线,然后求出这条之前的斜率和零点。需要注意k为无穷大的时候。

在然后在N个点中找出所有点在这条线的个数。直接粗暴。

下面是代码的实现:

C++ Code
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

class Solution

{

public:

int maxPoints(vector<Point> &points)

{

//下面使用以边为单位,进行搜索

if(points.size() < 3) return points.size();

int result = 0;

for(int i = 0; i < points.size() - 1; i++)

{

for(int j = i + 1; j < points.size(); j++)

{

int sign = 0;

int a, b, c;

if(points[i].x == points[j].x)

{

sign = 1;

}

else

{

a = points[j].x - points[i].x;

b = points[j].y - points[i].y;

c = a * points[i].y - b * points[i].x;

}

int count = 0;

for(int k = 0; k < points.size(); k++)

{

if((0 == sign && a * points[k].y == c + b * points[k].x) || (1 == sign && points[k].x == points[j].x))

{

count++;

}

}

if(count > result) result = count;

}

}

return result;

}

};
下面有一种更优化的解法:

就是以点为中心进行遍历,时间复杂度是O(N2)

代码实现如下所示:

C++ Code
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

/**

* 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)

{

// IMPORTANT: Please reset any member data you declared, as

// the same Solution instance will be reused for each test case.

unordered_map<float, int> mp;

int maxNum = 0;

for(int i = 0; i < points.size(); i++)

{

mp.clear();

mp[INT_MIN] = 0;

int duplicate = 1;

for(int j = 0; j < points.size(); j++)

{

if(j == i) continue;

if(points[i].x == points[j].x && points[i].y == points[j].y)

{

duplicate++;

continue;

}

float k = points[i].x == points[j].x ? INT_MAX : (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);

mp[k]++;

}

unordered_map<float, int>::iterator it = mp.begin();

for(; it != mp.end(); it++)

if(it->second + duplicate > maxNum)

maxNum = it->second + duplicate;

}

return maxNum;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: