|
| 1 | +package com.alg.top20.adhoc; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.Random; |
| 6 | + |
| 7 | +public class TwoSum { |
| 8 | + |
| 9 | + public static boolean twoSum1(int[] in, int target) { |
| 10 | + for (int i = 0; i < in.length; ++i) { |
| 11 | + for (int j = i + 1; j < in.length; ++j) { |
| 12 | + if (in[j] == target - in[i]) |
| 13 | + return true; |
| 14 | + } |
| 15 | + } |
| 16 | + return false; |
| 17 | + } |
| 18 | + |
| 19 | + // sort + binary search |
| 20 | + public static boolean twoSum2(int[] in, int target) { |
| 21 | + Arrays.sort(in); |
| 22 | + for (int i = 0; i < in.length; ++i) { |
| 23 | + if (Arrays.binarySearch(in, i + 1, in.length, target - in[i]) >= 0) |
| 24 | + return true; |
| 25 | + } |
| 26 | + return false; |
| 27 | + } |
| 28 | + |
| 29 | + // sort + 2-pointer approach |
| 30 | + public static boolean twoSum3(int[] in, int target) { |
| 31 | + Arrays.sort(in); |
| 32 | + int left = 0, right = in.length - 1; |
| 33 | + |
| 34 | + while (left < right) { |
| 35 | + if (in[left] + in[right] == target) |
| 36 | + return true; |
| 37 | + if (in[left] + in[right] < target) |
| 38 | + ++left; |
| 39 | + else |
| 40 | + --right; |
| 41 | + } |
| 42 | + return false; |
| 43 | + } |
| 44 | + |
| 45 | + // DS based - hashset |
| 46 | + public static boolean twoSum4(int[] in, int target) { |
| 47 | + HashSet<Integer> hset = new HashSet<Integer>(); |
| 48 | + for (int i = 0; i < in.length; ++i) { |
| 49 | + if (hset.contains(target-in[i])) |
| 50 | + return true; |
| 51 | + hset.add(in[i]); |
| 52 | + } |
| 53 | + return false; |
| 54 | + } |
| 55 | + |
| 56 | + public static void main(String[] args) { |
| 57 | + int n = Integer.parseInt(args[0]); |
| 58 | + int[] in = new int[n]; |
| 59 | + //testcase1 |
| 60 | + Random r = new Random(); |
| 61 | + for(int i = 0; i < in.length; ++i) |
| 62 | + in[i] = r.nextInt(3*n) + 1; |
| 63 | + int target = 0; |
| 64 | + //System.out.println(Arrays.toString(in)); |
| 65 | + long start = System.currentTimeMillis(); |
| 66 | + System.out.println(twoSum4(in, target)); |
| 67 | + long end = System.currentTimeMillis(); |
| 68 | + System.out.println("Time:" + (end-start)/1000.0 +"seconds"); |
| 69 | + |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments