Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
(失败)思路一:
枚举每两个点即每条线,如果是新的线,则加入记录,否则增加计数。
失败点1:有斜率k,截距b,和点个数n,3个参数需要记录。
如果用map自定义类型需要定义自定义<运算.实现繁琐;
如果用map相互嵌套,嵌套在内部的map似乎只能作为值不能作为键。
失败点2:极端情况下,这其实是O(N^4)的算法。
for point i
for point j
if line(i, j) is a new line
add a new line
else
increase count of the old line
思路二:
枚举每个点,统计通过这个点的所有直线上,最多有多少点。
注意点:1.斜率无穷大,即竖直的直线。
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 psize = points.size();
if (psize <= 2)
return psize;
int ans = 0;
for (int i = 0; i < psize; i++) {
int samepoints = 0;
int vertical = 0;
map<double, int> tangent;
for (int j = 0; j < psize; j++) {
if (points[i].x == points[j].x) {
if (points[i].y == points[j].y)
++samepoints;
else
++vertical;
}
else {
double k = (double) (points[j].y - points[i].y) / (points[j].x - points[i].x);
++tangent[k];
//cout << "tan k:" << k << " " << tangent[k] << endl;
}
}
map<double, int>::iterator it;
for (it = tangent.begin(); it != tangent.end(); ++it) {
ans = max(ans, samepoints + it->second);
}
ans = max(ans, samepoints + vertical);
ans = max(ans, samepoints);
}
return ans;
}
};
Sort a linked list in O(n log n) time using constant space complexity.
关于list的归并排序。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *sortList(ListNode *head) {
if (head == NULL)
return head;
if (head->next != NULL) {
ListNode *h1, *h2;
divide(head, h1, h2);
h1 = sortList(h1);
h2 = sortList(h2);
//print(h1);
//print(h2);
return mergesort(h1, h2);
}
else
return head;
}
void print(ListNode *head) {
cout << "print" << endl;
while (head != NULL) {
cout << head->val << endl;
head = head->next;
}
}
void divide(ListNode *head, ListNode * &h1, ListNode * &h2) {
h1 = head;
h2 = head->next;
ListNode *t1 = h1, *t2 = h2;
head = head->next;
while (true) {
if (head->next) {
t1->next = head->next;
head = head->next;
t1 = t1->next;
}else
break;
if (head->next) {
t2->next = head->next;
head= head->next;
t2 = t2->next;
}
else
break;
}
t1->next = NULL;
t2->next = NULL;
}
ListNode *mergesort(ListNode *h1, ListNode *h2) {
ListNode *ans;
if (h1->val < h2->val) {
ans = h1;
h1 = h1->next;
}
else {
ans = h2;
h2 = h2->next;
}
ListNode *p = ans;
while (h1 && h2) {
if (h1->val < h2->val) {
p->next = h1;
h1 = h1->next;
p = p->next;
}
else {
p->next = h2;
h2 = h2->next;
p = p->next;
}
}
if (h1) {
p->next = h1;
return ans;
}
if (h2) {
p->next = h2;
return ans;
}
}
};