JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.

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

Operations allowed:

Fill any of the jugs 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: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
Output: true
Explanation: The famous Die Hard example 

Example 2:

Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
Output: false

Example 3:

Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
Output: true

Code

592. Fraction Addition and Subtraction

贝祖定理

对任何整数 a,b,m, 关于未知数x和y的线性方程 ax + by = m 有整数解时当且仅当m是a及b的最大公约数d的倍数

12 和 42 的最大公约数是 6,则方程 12x + 42y = 6 有解。 事实上有 (-3)*12 + 1*42 = 6 以及 4*12 + (-1)*42 = 6

辗转相除法(欧几里得算法)

两个正整数x和y(x>y)的最大公约数(greatest common divisor), 等于其中较小的数(y)和两数相除余数(x%y)的最大公约数

更相减损法

两个正整数x和y(x>y)的最大公约数(greatest common divisor), 等于x-y的差值c和较小数y的最大公约数

class Solution {
    public boolean canMeasureWater(int x, int y, int z) {
        if(x + y < z) return false;
        if(x == z || y == z || x + y == z) return true;
        
        if(x > y) {
            return z % gcd2(x, y) == 0;
        } else {
            return z % gcd2(y, x) == 0;
        } 
    }
    
    private int gcd(int x, int y){
        return (x % y == 0) ? y : gcd(y, x % y);
    }

    private int gcd2(int x, int y){
        return (x % y == 0) ? y : gcd(y, x - y);
    }
}