Question

In: Computer Science

Data Structure in Java The following java method counts how many triples of integers in an...

Data Structure in Java

The following java method counts how many triples of integers in an array of n distinct integers sum to zero.

public static int count(int[] a) {
   int n = a.length;
   int count = 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 (a[i] + a[j] + a[k] == 0)
               count++;
         }
      }
   }
   return count;
}

For example: the following list

[8, -12, 9, 2, 4, -9, -2, 5]

has two triples that sim to zero: (8, -12, 4) and (4, -9, 5).

The problem here is that this is a bad solution to solve the problem and it takes Big O(n^3).

Find another solution to the problem that takes less than O(n^3) of time complexity

Hint 1: Sort the array first (use Java’s built-in Arrays.sort(int[] a)) method to sort the array first.

Hint 2: A pair a[i] and a[j] is part of a triple that sums to zero if and only if the value -(a[i] + a[j]) is in the array (but not a[i] or a[j]).

Solutions

Expert Solution

Please find your solution below and if doubt comment and do upvote.

CODE:

import java.util.Arrays;
public class Main
{
    //time complexity is O(N^2)
    public static int counts(int[] a) {
    int n = a.length;
    int count = 0;
    //sort the array
    Arrays.sort(a);
    //using loop tarverse the array
    for (int i = 0; i < n-1; i++) {
      int left=i+1;
      int right=n-1;
      int value=a[i];
      while(left<right)
      {
          //if sum equals 0 then increase count
          if((value+a[left]+a[right])==0){
              count++;
              left++;
              right--;
          }
          else if ((value+a[left]+a[right])<0)//else increase left index
          left++;
          else 
          right--;//decrease right index
      }
   }
   return count;//return count
}
        public static void main(String[] args) {
                int a[]={8, -12, 9, 2, 4, -9, -2, 5};
                System.out.println(counts(a));
                
        }
}

OUTPUT:


Related Solutions

Java Write a method that counts how many times one string appears in another string. The...
Java Write a method that counts how many times one string appears in another string. The method takes three input parameters: two Strings and one Boolean. The Boolean value determines whether the words are allowed to overlap each other. For example: When the method is called with input parameters (“balloon”, “oo”, false), it returns 1. When the method is called with input parameters (“hh”, “hhhhhh”, true) returns 5. When the method is called with input parameters (“cc”, “abcdefg”, true), returns...
Write a method in java (with out using startwith,boolean true false) count that counts how many...
Write a method in java (with out using startwith,boolean true false) count that counts how many times a substring occurs in a string:For example: count("is", "Mississippi") will return 2. also add comment besides code.
Java - Firstly, write a method, using the following header, that counts the number of prime...
Java - Firstly, write a method, using the following header, that counts the number of prime numbers between from and to (inclusive). public static int countPrimes(int from, int to) For example, countPrimes(11,19) returns 4 since 11, 13, 17 and 19 are primes. You can assume that someone has already written the following function to determine is an integer is prime or not. public static boolean isPrime(int i) // returns true if i is a prime number Secondly, write a program...
Java - Firstly, write a method, using the following header, that counts the number of prime...
Java - Firstly, write a method, using the following header, that counts the number of prime numbers between from and to (inclusive) . public static int countPrimes(int from, int to ) For example, countPrimes(11,19) returns 4 since 11, 13, 17 and 19 are primes. You can assume that someone has already written the following function to determine is an integer is prime or not. public static boolean isPrime(int i) // returns true if i is a prime number Secondly, write...
JAVA Write a program that reads the integers between -100 and 100 and counts the occurrences...
JAVA Write a program that reads the integers between -100 and 100 and counts the occurrences of each with ascending order. input: line1:number of figures line2:number Sample Input 5 -3 100 -1 -2 -1 Sample Output -3 1 -2 1 -1 2 100 1
Write a Java method that removes any duplicate elements from an ArrayList of integers. The method...
Write a Java method that removes any duplicate elements from an ArrayList of integers. The method has the following header(signature): public static void removeDuplicate(ArrayList<Integer> list) Write a test program (with main method) that prompts the user to enter 10 integers to a list and displays the distinct integers separated by exactly one space. Here is what the input and output should look like:      Enter ten integers: 28 4 2 4 9 8 27 1 1 9      The distinct...
Java Programming CS 209 Data Structure 1. Create a method that takes an ArrayList of String...
Java Programming CS 209 Data Structure 1. Create a method that takes an ArrayList of String and returns a copy of that ArrayList with no duplicates. The relative ordering of elements in the new ArrayList should be the same. Sample Input: {"qwerty", "asdfgh", "qwer", "123", "qwerty", "123", "zxcvbn", "asdfgh"} Sample Output: {"qwerty", "asdfgh", "qwer", "123", "zxcvbn"}
Java Data Structure Doubly Linked List /* * Complete the swap(int index) method * No other...
Java Data Structure Doubly Linked List /* * Complete the swap(int index) method * No other methods/variables should be added/modified */ public class A3DoubleLL<E> {    /*    * Grading:    * Swapped nodes without modifying values - 2pt    * Works for all special cases - 1pt    */    public void swap(int index) {        //swap the nodes at index and index+1        //change the next/prev connections, do not modify the values        //do not...
Using Java compare how many swaps it takes a 1000 element array of integers. Use both...
Using Java compare how many swaps it takes a 1000 element array of integers. Use both quick-sort and heap sort. Only count when you swap values. Run the test in best case (array starts in sorted order), average case (array starts in random order), and in worst case array is sorted in reverse order. Print out the number of swaps for each sorting method's results.
how many integers from 0 through 999,999 contain the digit 4 exactly twice? how many integers...
how many integers from 0 through 999,999 contain the digit 4 exactly twice? how many integers from 1 through 1000000 contain the digits 6 at least once
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT