SHARE
TWEET

find pair in array

DulcetAirman Nov 25th, 2018 88 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.claude_martin;
  2.  
  3. import java.util.Arrays;
  4. import java.util.TreeSet;
  5. import java.util.stream.IntStream;
  6.  
  7. public class SomeClass {
  8.  
  9.   public static void main(String[] args) {
  10.     {
  11.       var a = new int[] { 10, 15, 3, 7 };
  12.       var k = 17;
  13.       checkAndOutput(a, k);
  14.     }
  15.     {
  16.       var a = new int[] { -10, 15, 3, 7, -30 };
  17.       var k = -40;
  18.       checkAndOutput(a, k);
  19.     }
  20.     {
  21.       var a = IntStream.range(-100000, 100000).toArray();
  22.       var k = 99999;
  23.       checkAndOutput(a, k);
  24.     }
  25.     {
  26.       var a = IntStream.range(0, 10000000).toArray();
  27.       var k = -1;
  28.       checkAndOutput(a, k);
  29.     }
  30.   }
  31.  
  32.   static void checkAndOutput(final int[] a, final int k) {
  33.     System.out.format("a = %.100s%n", Arrays.toString(a));
  34.     System.out.format("k = %d%n", k);
  35.     System.out.format("result: %s%n", check(a, k));
  36.   }
  37.  
  38.   static boolean check(final int[] a, final int k) {
  39.     final var diff = new TreeSet<Integer>();
  40.     for (var i : a) {
  41.       if (diff.contains(i))
  42.         return true;
  43.       diff.add(k - i);
  44.       // note: this ignores that overflow can give false results
  45.     }
  46.     return false;
  47.   }
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top