1. 程式人生 > >1.4.2

1.4.2

for threesum sta 1.4 ID std import nbsp mod

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)); } }

1.4.2