365. Water and Jug Problem

You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs.

If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.

Operations allowed:

  • Fill any of the jugs completely with water.
  • Empty any of the jugs.
  • Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.

**Example 1: **

Input: x = 3, y = 5, z = 4
Output: True

Example 2:

Input: x = 2, y = 6, z = 5
Output: False

這道題實際上是道數學智力題,求解的關鍵就是判斷z能否整除x與y的最大公約數。當然,這道題有些隱藏約束,就是z<=x+y以及z可以為0,當然多過幾遍測試用例基本上就能察覺了。上代碼:

/**
 * @param {number} x
 * @param {number} y
 * @param {number} z
 * @return {boolean}
 */
var canMeasureWater = function (x, y, z) {
    const findDivisor = function (a, b) {
        while (b) {
            let c = a % b;
            a = b;
            b = c;
        }
        return a;
    };
    const divisor = findDivisor(x, y);
    if (z > x + y) {
        return false;
    }
    else if (z === x || z === y || z === 0) {
        return true;
    }
    return (z % divisor === 0);
};

需要一些優化的地方可能就是找最大公約數了,這里我選用了輾轉相除的方法。當然也有輾轉相減和暴力循環的方式。具體算法可以自行百度一下。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 問題描述 You are given two jugs with capacities x and y litre...
    codingXue閱讀 183評論 0 0
  • Question You are given two jugs with capacities x and y l...
    FlynnLWang閱讀 248評論 0 0
  • 買入三重標準:除了價格在移動平均線上方,第一,成交量不止兩倍于前四周的平均成交量,成交量的放大應持續幾周,第二,相...
    青青狐閱讀 358評論 0 0
  • 今日有雪。 午飯后,照例出門巡視一圈,消食賞景兩不誤。 雪后初霽,朦朦朧朧中別有一番景致,賞心悅目。 每天路過...
    蒼山暮雪閱讀 527評論 0 0
  • 四月,一個美麗的季節,有春暖花開,曾經在花海里徜徉,與櫻花有一次完美的約會,沉醉在花的海洋中,浪漫的花季總是讓人依...
    田田拾光閱讀 362評論 0 2