力扣---2020.4.12

面試題 16.03. 交點

//困難級別,直接複製大佬的答案
class Solution {
  public double[] intersection(int[] start1, int[] end1, int[] start2, int[] end2) {
    int x1 = start1[0], y1 = start1[1];
    int x2 = end1[0], y2 = end1[1];
    int x3 = start2[0], y3 = start2[1];
    int x4 = end2[0], y4 = end2[1];

    double[] ans = new double[2];
    Arrays.fill(ans, Double.MAX_VALUE);
    // 判斷兩直線是否平行
    if ((y4-y3)*(x2-x1) == (y2-y1)*(x4-x3)) {
      // 判斷兩直線是否重疊
      if ((y2-y1)*(x3-x1) == (y3-y1)*(x2-x1)) {
        // 判斷 (x3, y3) 是否在「線段」(x1, y1)~(x2, y2) 上
        if (isInside(x1, y1, x2, y2, x3, y3)) {
          updateRes(ans, x3, y3);
        }
        // 判斷 (x4, y4) 是否在「線段」(x1, y1)~(x2, y2) 上
        if (isInside(x1, y1, x2, y2, x4, y4)) {
          updateRes(ans, (double)x4, (double)y4);
        }
        // 判斷 (x1, y1) 是否在「線段」(x3, y3)~(x4, y4) 上
        if (isInside(x3, y3, x4, y4, x1, y1)) {
          updateRes(ans, (double)x1, (double)y1);
        }
        // 判斷 (x2, y2) 是否在「線段」(x3, y3)~(x4, y4) 上
        if (isInside(x3, y3, x4, y4, x2, y2)) {
          updateRes(ans, (double)x2, (double)y2);
        }
      }
    } else {
      // 聯立方程得到 t1 和 t2 的值
      double t1 = (double)(x3 * (y4 - y3) + y1 * (x4 - x3) - y3 * (x4 - x3) - x1 * (y4 - y3)) / ((x2 - x1) * (y4 - y3) - (x4 - x3) * (y2 - y1));
      double t2 = (double)(x1 * (y2 - y1) + y3 * (x2 - x1) - y1 * (x2 - x1) - x3 * (y2 - y1)) / ((x4 - x3) * (y2 - y1) - (x2 - x1) * (y4 - y3));
      // 判斷 t1 和 t2 是否均在 [0, 1] 之間
      if (t1 >= 0.0 && t1 <= 1.0 && t2 >= 0.0 && t2 <= 1.0) {
        ans[0] = x1 + t1 * (x2 - x1);
        ans[1] = y1 + t1 * (y2 - y1);
      }
    }
    if (ans[0] == Double.MAX_VALUE) {
      return new double[0];
    }
    return ans;
  }

  // 判斷 (x, y) 是否在「線段」(x1, y1)~(x2, y2) 上
  // 這裏的前提是 (x, y) 一定在「直線」(x1, y1)~(x2, y2) 上
  private boolean isInside(int x1, int y1, int x2, int y2, int x, int y) {
    // 若與 x 軸平行,只需要判斷 x 的部分
    // 若與 y 軸平行,只需要判斷 y 的部分
    // 若爲普通線段,則都要判斷
    return (x1 == x2 || (Math.min(x1, x2) <= x && x <= Math.max(x1, x2)))
            && (y1 == y2 || (Math.min(y1, y2) <= y && y <= Math.max(y1, y2)));
  }

  private void updateRes(double[] ans, double x, double y) {
    if (x < ans[0] || (x == ans[0] && y < ans[1])) {
      ans[0] = x;
      ans[1] = y;
    }
  }
}

面試題10- I. 斐波那契數列

class Solution {
    public int fib(int n) {
        if(n==0) return 0;
        if(n==1) return 1;
        int[] dp=new int[n+1];
        dp[1]=1;
        for(int i=2;i<=n;i++)
            dp[i]=(dp[i-1]+dp[i-2])%1000000007;
        return dp[n];
    }
}
class Solution {
    public int fib(int n) {
        int a = 0, b = 1, sum;
        for(int i = 0; i < n; i++){
            sum = (a + b) % 1000000007;
            a = b;
            b = sum;
        }
        return a;
    }
}

你知道的越多,你不知道的越多。
有道無術,術尚可求,有術無道,止於術。
如有其它問題,歡迎大家留言,我們一起討論,一起學習,一起進步

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章