[LeetCode] March 21 punch card -Day6

1 title kettle issues

description

There are two liter capacity are x and y-liter kettle and unlimited amount of water. Please judge whether By using these two kettle, z can be obtained exactly liters of water?
If z liters of water, the last two or more please use a kettle made to bloom.
You allow:
fill any kettle
emptied a bottle of any
other pouring water from a water bottle to bottle, filled or emptied until
Example 1: (From the famous "Die Hard" example)
Input: x = 3, y = 5 , z = 4
output: True
example 2:
input: x = 2, y = 6 , z = 5
output: False

answer

Ideas: first determine an extreme case, if the capacity of x and y is less than Z, never filled. If z is equal to the capacity of the x or y or x + y, it can be filled with water to fall down again.

At any one time, and only we can take the following actions:
assuming X> Y
1. pour into the pot X Y pot until filled or emptied; X Pot: cur_x-y Y Pot: + y
2. X Y pot pour into the pot, until filled or emptied; X pot: cur_x + y Y pot: -Y
3. the pot filled with X; X +
4. the Y pot filled; + y
5. the X pot emptied; the -X-
6. the pot the Y emptied. -y
each operation will only increase the total amount of water bucket x, increase y, reducing x, or reduce y.

Find a pair of integers a, b such that ax + by = z
be satisfied as long as the z ≤ x + y, and such a, b is present, then our goal is to be achieved.

Bezu Theorem: ax + by = z has a solution if and only if z is a x, y is a multiple of the greatest common divisor. So we just need to find the greatest common divisor x, y and z is to determine whether it can be a multiple of

gcd: find the greatest common divisor of x and y

class Solution {
    public boolean canMeasureWater(int x, int y, int z) {
        if(x + y < z) return false;
        if(z == 0 || z == x + y || z == x || z == y) return true;
        int gcd = gcd(x, y);
        return z % gcd == 0;
    }
    public int gcd(int a, int b){
        if(b == 0){
            return a;
        }
        return gcd(b, a % b);
    }
}
Published 29 original articles · won praise 65 · views 5034

Guess you like

Origin blog.csdn.net/xd963625627/article/details/105003879