ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode-365 Water and Jug Problem

2019-07-25 14:50:44  阅读:247  来源: 互联网

标签:water return jugs int 复杂度 Water 水壶 Problem 365


题目描述

You are given two jugs with capacities xand 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.

 

题目大意

两个大小分别为x和y升的水壶,可以无限次的给水壶充满水,并且两个水壶之间可以互相倒水,是否可以实现两个水壶中的水相加等于z。

 

示例

E1

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

E2

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

 

解题思路

根据LeetCode@lblbxuxu2的思路,用v来表示当前的获得的水的总量,

  当v < x时,能做的有意义的操作只能是将y灌满,因此:v += y

  当v > x时,能做的有意义的操作只能是将x清空,因此:v -= x

循环判定是否存在满足v = z的情况。

 

复杂度分析

时间复杂度:O(N)

空间复杂度:O(1)

 

代码

class Solution {
public:
    bool canMeasureWater(int x, int y, int z) {
        if(x + y == z)
            return true;
        if(x + y < z)
            return false;
        // 若x比y小,则将两个数字互换
        if(x < y) {
            int tmp = x;
            x = y;
            y = tmp;
        }
        
        int v = 0;
        while(1) {
            if(v < x)
                v += y;
            else
                v -= x;
            if(v == z)
                return true;
            if(v == 0)
                return false;
        }
    }
};

 

标签:water,return,jugs,int,复杂度,Water,水壶,Problem,365
来源: https://www.cnblogs.com/heyn1/p/11244169.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有