首页 > 其他分享 >LeetCode 365. Water and Jug Problem

LeetCode 365. Water and Jug Problem

时间:2022-09-25 07:44:05浏览次数:72  
标签:jug2Capacity water jug1Capacity jug int Water targetCapacity Problem 365

原题链接在这里:https://leetcode.com/problems/water-and-jug-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

Constraints:

  • 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106

题解:

It is find found if capacity1 * a + capacity2 * b = totalCapacity.

If a or b is negative, then it means empty jug. e.g. cap1 = 4, cap2 = 6, totalCapacity = 8. Return true.

Fill cap2 with 6, move 4 to cap1, empty cap1, move the rest 2 from cap2 to cap1.

Fill cap2 again with 6. Totally we have -1 * 4 + 2 * 6 = 8.

Time Complexity: O(log(min(jug1Capacity, jug2Capacity))). gcd takes O(log(min(jug1Capacity, jug2Capacity))).

Space: O(1). regardless stack.

AC Java:

 1 class Solution {
 2     public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
 3         // We only have one jug1 and one jug2.
 4         if(jug1Capacity + jug2Capacity < targetCapacity){
 5             return false;
 6         }
 7         
 8         // In case jug 1 or 2 has 0 capacity.
 9         if(jug1Capacity == targetCapacity || jug2Capacity == targetCapacity){
10             return true;
11         }
12         
13         return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0;
14     }
15     
16     private int gcd(int a, int b){
17         if(b == 0){
18             return a;
19         }
20         
21         return gcd(b, a % b);
22     }
23 }

 

标签:jug2Capacity,water,jug1Capacity,jug,int,Water,targetCapacity,Problem,365
From: https://www.cnblogs.com/Dylan-Java-NYC/p/16727188.html

相关文章