1.4.2

question:

Modify ThreeSum to work properly even when the int values are so large that adding two of them might cause overflow.

answer:

import edu.princeton.cs.algs4.*;

public class ThreeSum
{
    public static int count(int[] a) 
    {
        int N = a.length;
        int cnt = 0;
        for(int i = 0; i < N; i++)
        {
            for(int j = i+1; j < N; j++)
            {
                for(int k = j + 1; k < N; k++)
                {
                    if((long)a[i] + a[j] + a[k] == 0)//只要判断时不溢出就行
                        cnt++;
                }
            }
        }
        return cnt;
    }
    
    public static void main(String[] args)
    {
        int[] a = In.readInts(args[0]);
        StdOut.println(count(a));
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9094440.html
今日推荐