Java --"Time Limit Exceeded "--but why it work on my eclipse?


  • 0
    X

    code here ,last input {5,8,1,6}

     ArrayList<Integer> temp = new ArrayList<Integer>();
            int sum=1;
            for(int i=0;i<num.length;i++){
            	temp.add(num[i]);
            	sum*=(i+1);
            }
            int count=0;
            ArrayList<ArrayList<Integer>> 
    	        temp2 = new ArrayList<ArrayList<Integer>>();
            Object[] b;
            while(count<sum){
                Collections.shuffle(temp);
            	b=temp.toArray();
            	if(!temp2.contains(Arrays.asList(b))){
            		temp2.add(new ArrayList(Arrays.asList(b)));
            	    count++;
            	}
            }
           return temp2;

  • 0
    I

    When count getting closer to sum, most of the time you shuffled it only gets you a result that already in the temp2.


  • 0
    M

    Nothing is wrong with your code, if you are willing to wait. As iambright said, however, as you get closer and closer to sum, you get duplicate results more and more often, until the final permutation has only a 1/sum chance of being chosen. Your algorithm will eventually get it, but it will take much longer than is needed, which is one of the meanings of "Time Limit Exceeded." That is why Eclipse works, but Leetcode doesn't.

    The other meaning, which I assume you are thinking of, is when there is an infinite loop preventing an answer ever being sent back. In that case, you are correct, neither Eclipse nor Leetcode would work. If the algorithm just takes much more time than needed, as in this problem, you get "Time Limit Exceeded" in Leetcode, and a working algorithm in Eclipse.


Log in to reply
 

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