What is the difference between two similar algorithms of Java – 3sum?

I am here http://www.leetcode.com/onlinejudge A 3sum problem was found on the, as follows:

Given an array s of N integers, are there elements a, B, C in s so that a, B, C = 0? Find all unique triples in the array, and their sum is zero

Note: the elements in triple (a, c) must be non descending (i.e. a ≤ B ≤ C) the solution set must not contain duplicate triples

For example,given array S = {-1 0 1 2 -1 -4},A solution set is:
(-1,1)
(-1,-1,2)

I visited the website and found the proposed solution:

public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
    Arrays.sort(num);
    HashSet<ArrayList<Integer>> lstSoln = new HashSet<ArrayList<Integer>>();

    ArrayList<Integer> tempArr = null;
    for (int i = 0; i < num.length; i++) {
        int j = i + 1;
        int k = num.length - 1;
        while (j < k) {
            int sum3 = num[i] + num[j] + num[k];
            if (sum3 < 0) {
                j++;
            } else if (sum3 > 0) {
                k--;
            } else {
                tempArr = new ArrayList<Integer>();
                Collections.addAll(tempArr,num[i],num[j],num[k]);
                lstSoln.add(tempArr);
                j++;
                k--;
            }
        }
    }

    return new ArrayList<ArrayList<Integer>>(lstSoln);
}

As you can see, this takes each number and then uses two numbers after the current index So, obviously, once we reach the first positive number, we just do a useless loop, and we won't find any triples added to 0 So I modified the solution and added a condition

if (num[i] > 0)
    break;

In fact, this should reduce the number of times the for loop runs, thereby reducing the time it takes to find a solution I even check by adding a counter and incrementing it at each if () Every time the counter of my solution is less than the counter of the proposed solution

However, when I enter my modified solution on the check page, it will cause a timeout error or display longer than the unmodified version! I want to know what's wrong with my modification?

Solution

I didn't see any problems with your solution. I tried my local solution and added a faster solution I use system Nanotime() checked the time difference Due to network problems, you may face a timeout error on the solution check page

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>