[leetCode刷题笔记]2017.04.04

67. Add Binary

真不知道String builder还有reverse方法。。。本来都准备用Stack了。。。

public class Solution {
    public String addBinary(String a, String b) {
       
        StringBuilder sb = new StringBuilder();
        int i = a.length() - 1, j = b.length() - 1, promote = 0;
        while (i >=0  || j >= 0) {
            int sum = promote;
            if (i >= 0) sum += a.charAt(i--) - '0';
            if (j >= 0) sum += b.charAt(j--) - '0';
            sb.append(sum % 2);
            promote = sum / 2;
        }
        if (promote != 0) sb.append(promote);
        return sb.reverse().toString();
    }
}

149. Max Points on a Line

这道题没有AC,因为double对这个test case:

[[0,0],[94911151,94911150],[94911152,94911151]]精度不够。

比较好的方法是产生最大公约数,再用x 和y一起作为key。


/**
 * 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.length <= 1) {
            return points.length;
        }
        
        
        int max = 0;
        for (int i = 0; i < points.length - 1; i++) {
            int dup = 1;
            Map<Double, Integer> pointMap = new HashMap<Double, Integer>();
            for (int j = 0; j < points.length; j++) {
                if(j==i) continue;
                if(points[i].y==points[j].y && points[i].x==points[j].x) {
                    dup++;
                    continue;
                }
                double grad = getGrad(points[i], points[j]);
                if (!pointMap.containsKey(grad)) {
                    pointMap.put(grad, 1);
                    
                }
                else {
                    pointMap.put(grad, pointMap.get(grad) + 1);
                    
                }
                
            }
            if (pointMap.size() == 0) max=max > dup ? max : dup;
            for (Double k : pointMap.keySet()) {
                max = max < pointMap.get(k) + dup ? pointMap.get(k) + dup: max;
                
            }
            
        }

        return max;
    }
    
    private double getGrad(Point a, Point b) {
        int xDiff = a.x - b.x;
        int yDiff = a.y - b.y;
        
        if (xDiff == 0) return Double.MAX_VALUE;
        return (double) yDiff / xDiff;
        
        
        
    } 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值