Passed 3SumClosest with a bug in algorithm.


  • 0
    C
     public class Solution {
            public int threeSumClosest(int[] num, int target) {
                Arrays.sort(num);
                int i = 0, j = 1, k = num.length - 1;
                int ans = num[0] + num[1] + num[2];
                while(i < j && j < k) {
                    int s = num[i] + num[j] + num[k];
                    if( s == target) return s;
                    else {
                        if (Math.abs(target - ans) > Math.abs(target - s) ) ans = s;
                        
                        if (s > target) k--;
                        else {
                            if(i < j - 1) i++;
                            else j++;
                        }
                    }
                }
                return ans;
            }
        }
    

    Above is my buggy code which passed the OJ.
    Please add some test cases such as:

    int[] num = {1, 2, 4, 8, 16, 32, 64, 128};
    int target = 82;

  • 0
    C

    I was not asking questions about my code. The problem is LeetCode should have more test cases to prevent wrong algorithms from passing the OJ. I just tested this code today and it was still accepted.


  • 0
    C

    By the way, I posted my OP after I read the FAQ.
    I found a bug in my code but it was accepted by the judge. Could I ask a question here?

    Yes, absolutely! Please mention at least few test cases that should be added to the judge, and remember to include your full buggy code in the question itself. Your contribution will be greatly appreciated by all users of the LeetCode community.


  • 0

    Thanks for your test case, @chern1502. You are correct, and so sorry for accidentally closing your question. I will add the test case soon.


  • 0

    Test case already added. Thanks again @chern1502!


Log in to reply
 

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