Time limit exceed


  • 0
    W
    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> sumList = new ArrayList<List<Integer>>();
            
            for(int x= 0 ; x < nums.length; x++){
                for(int y = x+1; y < nums.length; y++){
                    for(int z = y + 1; z < nums.length; z++){
                        
                        if(nums[x] + nums[y] + nums[z] == 0){
                            
                            List<Integer> result = new ArrayList<Integer>();
                            result.add(nums[x]);
                            result.add(nums[y]);
                            result.add(nums[z]);
                            Collections.sort(result);
                            
                            if(!sumList.contains(result)){
                                sumList.add(result);
                            }
                            
                        }
                    }
                }
            }
            
            return sumList;
            
        }
    }

  • 0
    N

    I think this is because the time complexity of your algorithm is O(n^3). Try optimize it to make it faster.


Log in to reply
 

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