题目链接: LintCode 炼码
平面上有N个点,任意2个点确定一条直线,求出所有这些直线中,斜率最大的那条直线所通过的两个点。
(点的编号为1-N,如果有多条直线斜率相等,则输出所有结果,按照点的X轴坐标排序,正序输出。数据中所有点的X轴坐标均不相等,且点坐标为随机。)
java 版本答案
public class LC996 {
static class Point {
int x;
int y;
Point() {
x = 0;
y = 0;
}
Point(int a, int b) {
x = a;
y = b;
}
}
public static List getPoints(Point[] points) {
/*
思路:
可以先将N个点按x进行排序。
斜率k最大值为max(斜率(point[i],point[i+1])) 0<=i() {
@Override
public int compare(Info a, Info b) {
//题目规定坐标x没有相等的情况。
//因此返回值要么大于0,要么小于0
return a.point.x-b.point.x;
}
});
int[] pos = {-1,-1};
double maxXL=-1;
for (int i = 1; i maxXL){
maxXL= xl;
pos[0]=infos[i-1].index;
pos[1]=infos[i].index;
}
}
List ans = new ArrayList<>();
ans.add(pos[0]);
ans.add(pos[1]);
Collections.sort(ans);
return ans;
}
static class Info{
Point point;
int index;
public Info(Point p,int i){
point =p;
index=i;
}
}
public static void main(String[] args) {
//int[][] arr1 = {{0, 0}, {1, 2}, {2, 3}, {3, 4}};
// int[][] arr2 = {{0, 0}, {1, 0}, {2, 0}};
int[][] arr3 = {{-1430, -18732}, {-1441, -22482}, {-5817, 24054}, {14741, 25893}, {-24664, -28094}, {29797, 17247}, {-28277, 30109}, {13543, 18680}, {-13399, -13325}, {26225, 15630}};
int[][] arr4 = {{13516,-22789},{-24730,22395},{21973,26520},{-23831,-13786},{-7900,1988},{11994,-16848},{24977,-2475},{8226,-22689},{-11876,-4694},{5941,-29624}};
//Point[] p1 = new Point[arr1.length];
//Point[] p2 = new Point[arr2.length];
Point[] p3 = new Point[arr3.length];
Point[] p4 = new Point[arr4.length];
// for (int i = 0; i < arr1.length; i++) {
// p1[i] = new Point(arr1[i][0], arr1[i][1]);
// }
//
// for (int i = 0; i < arr2.length; i++) {
// p2[i] = new Point(arr2[i][0], arr2[i][1]);
// }
//
for (int i = 0; i < arr3.length; i++) {
p3[i] = new Point(arr3[i][0], arr3[i][1]);
}
for (int i = 0; i < arr4.length; i++) {
p4[i] = new Point(arr4[i][0], arr4[i][1]);
}
// System.out.println(getPoints(p1));
// System.out.println(getPoints(p2));
System.out.println(getPoints(p3));
System.out.println("答案:"+getPoints(p4));
}
}
C++ 版本答案
#include
#include
#include
#include
#define ll long long int
const int INF=0x3f3f3f3f;
using namespace std;
struct head
{
int x,y,c; //c用来记录是第几个点
}a[10000];
bool cmp(head x,head y)
{
if(x.x==y.x)
return x.y>m;
int arr1[10][2] = {{-1430, -18732}, {-1441, -22482}, {-5817, 24054}, {14741, 25893}, {-24664, -28094}, {29797, 17247}, {-28277, 30109}, {13543, 18680}, {-13399, -13325}, {26225, 15630}};
int arr[10][2] = {{13516,-22789},{-24730,22395},{21973,26520},{-23831,-13786},{-7900,1988},{11994,-16848},{24977,-2475},{8226,-22689},{-11876,-4694},{5941,-29624}};
for(int i=0;i<10;i++)
{
a[i].x = arr[i][0];
a[i].y= arr[i][1];
a[i].c=i;
// cin>>a[i].x>>a[i].y;
// if(i!=0)
// a[i].c=a[i-1].c+1;
}
sort (a,a+10,cmp);
double max=-100000;
for(int i=1;i<10;i++)
{
double n = ((double)a[i].y-a[i-1].y)/((double)a[i].x-a[i-1].x);
cout<n)
{
max=max;
}else
{
max=n;
aa=a[i].c;
bb=a[i-1].c;
}
}
cout << "result is: ";
cout<