Why my code got TLE but work well in Permutation I?


  • 0
    S

    Can Anyone help me, please?
    I think this code can get the right answer.But got TLE at [3,3,0,0,2,3,2], this test case.

    public class Solution {
            public List<List<Integer>> permuteUnique(int[] nums) {
                Arrays.sort(nums);
                LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();
                result.add(new ArrayList<Integer>());
                for(int i = 0; i < nums.length; i++){
                    while(result.peekFirst().size() == i){
                        List<Integer> curr = result.removeFirst();
                        curr.add(nums[i]);
                        for(int j = 0; j < curr.size()-1; j++){
                            List<Integer> tmp = new ArrayList<>(curr);
                            if(nums[i] != curr.get(j)){
                                int m = tmp.get(j);
                                int n = tmp.get(tmp.size()-1);
                                tmp.set(j, n);
                                tmp.set(tmp.size()-1, m);
                                result.add(tmp);
                            }
                        }
                        result.add(curr);
                    }
                }
                return result;
            }
        }

Log in to reply
 

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