zoukankan      html  css  js  c++  java
  • 【leetcode】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 zlitres using these two jugs.

    Operations allowed:

    • Fill any of the jugs completely.
    • 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.

    解题分析:

    这是我本科时算法课上到一道经典题。两个瓶子可能量出的水是两个瓶子容量最大公约数的倍数。所以只要判断z是否可以被x,y的最大公约数整除即可。

    具体代码:

     1 public class Solution {
     2       public static boolean canMeasureWater(int x, int y, int z) {
     3         int n=Math.max(x, y);
     4         int m=Math.min(x, y);
     5         x=n;
     6         y=m;
     7         if(z>x)
     8             return false;
     9         if(z==x||z==y)
    10             return true;
    11         n=fun(x,y);
    12         return z%n==0;
    13     }
    14     //求x,y的最大公约数
    15     public static int fun(int x,int y){
    16         if(x%y==0)
    17             return y;
    18         while(x%y!=0){
    19             int m=Math.max(x-y, y);
    20             int n=Math.min(x-y, y);
    21             x=m;
    22             y=n;
    23         }
    24         return y;
    25     }
    26 }
  • 相关阅读:
    js获取浏览器和屏幕的各种宽度高度
    闭包
    原型与原型链
    vuex
    微信小程序天使童装答辩
    vue脚手架本地开发跨域请求设置
    mvvm和mvc
    Vue 中 methods,computed, watch 的区别
    keep-alive
    YII2组件之GridView
  • 原文地址:https://www.cnblogs.com/godlei/p/5614992.html
Copyright © 2011-2022 走看看