Advertisement
Guest User

Untitled

a guest
Jan 30th, 2015
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class ThreeSum {
  4. public static int threeSumCubic(int[] arr) {
  5. int count = 0;
  6. for (int i=0; i<arr.length; i++) {
  7. for (int j=i+1; j<arr.length; j++) {
  8. for (int k=j+1; k<arr.length; k++) {
  9. if (arr[i] + arr[j] + arr[k] == 0) {
  10. count++;
  11. }
  12. }
  13. }
  14. }
  15. return count;
  16. }
  17.  
  18. public static int threeSumQuadratic(int[] arr) {
  19. Arrays.sort(arr);
  20. int count = 0;
  21. for (int i=0; i<arr.length-2; i++) {
  22. int j = i+1;
  23. int k = arr.length-1;
  24. while (j < k) {
  25. int sum = arr[i] + arr[j] + arr[k];
  26. if (sum < 0) {
  27. j++;
  28. } else if (sum > 0) {
  29. k--;
  30. } else {
  31. count++;
  32. j++;
  33. k--;
  34. }
  35. }
  36. }
  37. return count;
  38. }
  39.  
  40. public static void main(String[] args) {
  41. int[] arr = new int[]{0, 0, 0, 0};
  42. System.out.println(threeSumQuadratic(arr));
  43. System.out.println(threeSumCubic(arr));
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement