嵌套for-while循环中超出时间限制

时间:2016-10-29 19:01:32

标签: java for-loop runtimeexception

有人可以帮我理解这次限时超限的来源吗?上下文是在这个threeSum方法中,给定一个数组,我试图记录三个数字的所有可能组合,加起来为0.原始问题来自:https://leetcode.com/problems/3sum/

public class Solution {
public List<List<Integer>> threeSum(int[] nums) {

    List<List<Integer>> retList = new ArrayList<List<Integer>>();

    Arrays.sort(nums); // O(nlogn)

    for (int i=0; i<nums.length-1; i++){
        int pleft;
        int pright;
        if (i!=0){
            pleft = i-1;
            while((nums[pleft]==nums[i]) && (pleft-1 >=0)){
                pleft--;
            }
        } else {
            pleft = i; 
        }
        if (i!=nums.length-2){
            pright = i+1;
            while((nums[pright]==nums[i]) && (pright+1 < nums.length-1)){
                pright++;
            }
        } else {
            pright = i;
        }
        int sum;
        while (true){
            sum = nums[pleft]+nums[pright]+nums[i];
            if (sum==0){
                List<Integer> temp = new ArrayList<Integer>();
                temp.add(nums[pleft]);
                temp.add(nums[pright]);
                temp.add(nums[i]);
                retList.add(temp);
                if (pleft-1>=0) pleft--;
                if (pright+1<nums.length-1) pright++;
            } else if (sum>0){
                if (pleft-1>=0) pleft--;
            } else { // less than zero
                if (pright+1<nums.length-1) pright++;
            }

        }
    }


    return retList;
}

}

1 个答案:

答案 0 :(得分:1)

您没有突破while(true)循环。该代码将永远运行,您将无法返回值。您需要添加break或将while (true)更改为while (condition)