在LeetCode上写了一段代码。
链接为:https://leetcode.com/problems/erect-the-fence/#/description
运用了Gift wrapping aka Jarvis march
完成。
本来很简单的程序始终不能最后AC
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* }
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
struct Point* outerTrees(struct Point* points, int pointsSize, int* returnSize) {
double costhta(double x1, double y1, double x2, double y2);
if(pointsSize == 1)
{
*returnSize = 1;
return points;
}
struct Point* ret;
ret = (struct Point*)malloc(sizeof(struct Point)*(pointsSize+1));
int i, j = 0, pushed, befpush;
double theta, maxtheta, vectorx, vectory;
ret[0].x = points[0].x;
ret[0].y = points[0].y;
pushed = 0;
for(i = 1; i < pointsSize; i++)
{
if(points[i].x < ret[0].x)
{
ret[j].x = points[i].x;
ret[j].y = points[i].y;
pushed = i;
}
}
j++;
befpush = pushed;
pushed = 0;
if(befpush == 0) pushed = 1;
maxtheta = costhta(0, 1, (points[pushed].x - ret[j-1].x), (points[pushed].y - ret[j-1].y));
ret[j].x = points[pushed].x;
ret[j].y = points[pushed].y;
for(i = 0; i < pointsSize; i++)
{
if(i == befpush || i == pushed) continue;
theta = costhta(0, 1, (points[i].x - ret[j-1].x), (points[i].y - ret[j-1].y));
if(theta == maxtheta)
{
if(abs(points[i].x-ret[j-1].x) < abs(points[pushed].x - ret[j-1].x))
{
pushed = i;
ret[j].x = points[i].x;
ret[j].y = points[i].y;
}
}
if(maxtheta < theta)
{
pushed = i;
maxtheta = theta;
ret[j].x = points[i].x;
ret[j].y = points[i].y;
}
}
j++;
while(true)
{
vectorx = ret[j-1].x - ret[j-2].x;
vectory = ret[j-1].y - ret[j-2].y;
befpush = pushed;
pushed = 0;
if(befpush == 0) pushed = 1;
maxtheta = costhta(vectorx, vectory, (points[pushed].x - ret[j-1].x), (points[pushed].y - ret[j-1].y));
ret[j].x = points[pushed].x;
ret[j].y = points[pushed].y;
for(i = 0; i < pointsSize; i++)
{
if(i == befpush || i == pushed) continue;
theta = costhta(vectorx, vectory, (points[i].x - ret[j-1].x), (points[i].y - ret[j-1].y));
if(fabs(theta - maxtheta) < 0.000000001)
{
if(abs(points[i].x-ret[j-1].x)+abs(points[i].y - ret[j-1].y) < abs(points[pushed].x - ret[j-1].x) + abs(points[pushed].y - ret[j-1].y))
{
pushed = i;
ret[j].x = points[i].x;
ret[j].y = points[i].y;
}
}
if(theta - maxtheta > 0.00000001)
{
pushed = i;
maxtheta = theta;
ret[j].x = points[i].x;
ret[j].y = points[i].y;
}
}
if( (ret[j].x == ret[0].x) && (ret[j].y == ret[0].y) )
{
break;
}
if( maxtheta == -1)
{
printf("i\n");
break;
}
j++;
}
*returnSize = j;
return ret;
}
double costhta(double x1, double y1, double x2, double y2)
{
return (x2 * x1 + y1 * y2)/sqrt(x2*x2 + y2*y2)/sqrt(x1*x1 + y1*y1);
}
浮点数大小比较,本来应该相同的两个数,但由于计算误差,导致两者不同,更要命的是这导致其中某处判断出了问题,将结果改变。
所以 以后浮点数的比较 double a < double b,当结果不可预期时,最好改为double b - double a > 0.00000001