Java 3-SUM代码的行为出乎意料



我已经尝试解决3和问题,其中您读取数组的元素数量,然后从文件中读取数组本身,然后将三元组发送到另一个文件。

对于那些不知道三和问题的人,这里是:三和问题是问给定的n个实数集合是否包含三个元素,和为零。如果是,则返回三元组。

这是我的代码:
   import java.util.*;
import java.io.*;
public class Main 
    { public static void main(String[] args) throws Exception            
        { int number_elements=0;
        int[] array_elements=null;
        File file = new File("date.in.txt");     
        File file2 = new File("date.out.txt");
        try  
            {Scanner input = new Scanner(file);
            number_elements=input.nextInt();
            array_elements = new int[number_elements];
            int contor=0;
            while(input.hasNext())
                { array_elements[contor]=input.nextInt();
                contor++; }}
        catch(IOException e)
            { System.out.println("eroare"); }

        Arrays.sort(array_elements);

        try 
            { PrintWriter output = new PrintWriter(file2); 
            output.print("The triplets who sum to 0: ");
            for(int i=0;i<number_elements-2;i++)
                { int j=i+1;
                int k=number_elements-1;
                while(k>=j)
                    { int temp=array_elements[i]+array_elements[j]+array_elements[k];
                    if(temp==0)
                        { output.println("( "+array_elements[i]+", "+array_elements[j]+", "+array_elements[k]+" )n");
                        break; }
                    else if(temp>0)
                        k--;
                    else if(temp<0)
                        j++; }}
           output.close(); }
        catch(IOException e)
            { System.out.println("eroare"); }
        }}

输入:

8

3 1 2 -5 -2 10 7 3

和为0的三元组:(-5,-2,7)

(- 2,1,1)

我真的不明白为什么,我的意思是,

(- 2,1,1)

甚至不属于我的数组。如果有人能指出我的错误,我会非常感激。

(-2,1,1)不属于您的数组。但是,-2和1可以。所以你可以得出"1"被重复的结论。要解决这个问题,应该将while循环的条件更改为k > j,而不是k >= j

最新更新