2 test cases can't be passed.Was using a HashSet.Anybody can help?


  • 0

    The code works for 26 cases but can't pass the rest 2.One failing test: x=104659,y=104677,z=142424

    Don't know why.The idea is simple. We're given a small jar and a large jar, we start from filling the larger full, and pour water into smaller until the smaller one gets totally filled.Then we empty the smaller and keep filling it using the water remaining in the larger one;if the remaining water in the larger one isn't enough for totally filling the smaller, we empty the larger one by pouring the remaining water into smaller , then refill the larger until full,and fill the smaller one like above.

    We use a variable "large" to denote water amount in the larger.For each loop we check if "large" is the amount desired, if it is we return TRUE; if "large" is already in a HashSet, that means we've once come to this point and this it's infinite loop(we'll come to this existing amount again if we keep doing this),so return FALSE; if it's neither TRUE nor FALSE, we save "large" in the HashSet, update "large" in the larger to be ready for next loop.

    Anyone can help I truly appreciate it!!

     public class Solution{
    public boolean canMeasureWater(int x,int y,int z){
    	if(x<y){
    		return canMeasureWater(y,x,z);
    	}
    	//x denote container with larger capacity,y denote the one with smaller capacity
    	if(x+y==z||x==z||y==z){
    		return true;
    	}else if(x+y<z){
    		return false;
    	}else{
    		HashSet<Integer> set=new HashSet<Integer>();
    		int larger=x;
    		while(true){
    			if(larger==z){
    				return true;
    			}else if(set.contains(larger)){
    					return false;
    			}else{
    				set.add(larger);
    				if(larger>=y){
    					larger=larger-y;
    				}else{
    					larger=x-(y-larger);
    				}
    			}
    		}
    	}
    }
    

    }


  • 0

    So you're not told why you fail, like Wrong Answer or Time Limit Exceeded?


  • 0

    Sorry I forgot to mention the result.Pretty new to Leetcode. OJ says wrong answer, passed 26 tests and failed 2. The failed on is x=104659,y=104677,z=142424.OJ says this test should've return True while mine return False.


  • 0
    4

    let's say y = 3, x = 11 and z = 13. You only test numbers less or equal to x, which is 11 in your program and it will fail eventually. you should add that when larger < y, you test if (larger + x == z)


  • 0

    This test case is helpful. I have added your test case, thanks. :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.