1. Max Points on a Line 这道题思路不难,对于每一个点,然后历遍后面的点,计算斜率然后储存到map里。需要有两个特殊情况,一个是垂直,其实也可以存成斜率1.0,另一个是重复,最后要注意存储的时候要注意最后最后计算数目的时候不能忘记点本身,还要注意在计算斜率的时候要先转成double然后再计算。这个题应该还可以存储dup的节点,这样以后遇到了就不用重复计算了。
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public int maxPoints(Point[] points) {
if (points == null || points.length == 0){
return 0;
}
HashMap<Double, Integer> res = new HashMap<Double, Integer>();
int max = 0;
for (int i = 0; i < points.length; i++){
int ver = 0;
int dup = 0;
for (int j = i + 1; j < points.length; j++){
if (points[j].x == points[i].x) {
if (points[j].y == points[i].y) {
dup++;
} else {
ver++;
}
}else {
double k;
if (points[j].y == points[i].y) {
k = 0.0;
} else {
k = ((double)(points[j].y - points[i].y)/(points[j].x - points[i].x));
}
if (res.containsKey(k)){
res.put(k, res.get(k) + 1);
} else {
res.put(k, 1);
}
}
}
for (int num : res.values()){
max = Math.max(max, num + dup + 1);
}
max = Math.max(max, ver + dup + 1);
res.clear();
}
return max;
}
}
2. Candy 这个题不算难直接就想出来了,可以从左向右历遍,然后再从右往左确保满足条件
public class Solution {
public int candy(int[] ratings) {
if (ratings == null || ratings.length == 0){
return 0;
}
int[] candy = new int[ratings.length];
candy[0] = 1;
for (int i = 1; i < ratings.length; i++){
if (ratings[i] > ratings[i-1]){
candy[i] = candy[i-1] + 1;
} else {
candy[i] = 1;
}
}
for (int i = ratings.length - 2; i >= 0; i--){
if (ratings[i] > ratings[i+1]){
if (candy[i] <= candy[i+1])
candy[i] = candy[i+1] + 1;
}
}
int num = 0;
for (int i = 0; i < ratings.length; i++){
num = num + candy[i];
}
return num;
}
}