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 - 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
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"}
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
use java for : 1. Write a method called indexOfMax that takes an array of integers...
use java for : 1. Write a method called indexOfMax that takes an array of integers and returns the index of the largest element. 2. The Sieve of Eratosthenes is “a simple, ancient algorithm for finding all prime numbers up to any given limit” (https://en.wikipedia. org/wiki/Sieve_of_Eratosthenes).Write a method called sieve that takes an integer parameter, n, and returns a boolean array that indicates, for each number from 0 to n -1, whether the number is prime.
FOR JAVA Write a method called findNum that takes a two-dimension array of integers and an...
FOR JAVA Write a method called findNum that takes a two-dimension array of integers and an int as parameters and returns the number of times the integer parameter appears in the array. For example, if the array (as created by the program below) is 10 45 3 8 2 42 3 21 44 And the integer parameter is 3, the value returned would be 2 (the number 3 appears two times in the array) public class HomeworkA { public static...
How is this method coded in Java?
How is this method coded in Java?
Implement a method that does the following: (a) Create a Map data structure to hold the...
Implement a method that does the following: (a) Create a Map data structure to hold the associations between player name (key) and team affiliation (value) (b) Add at least 5 mappings to the map (c) Print out the current roster of mappings (d) Assuming some time has passed, change some of the mappings to simulate the players changing their affiliations (e) Again, print out the current roster of mappings 3. Implement a main method that calls the above methods, demonstrating...
java/ netbeans Write a recursive method smallestNumber which takes an ArrayList of Integers as input and...
java/ netbeans Write a recursive method smallestNumber which takes an ArrayList of Integers as input and returns the smallest number in the array. You can use a helper method if needed. Write a main method that asks the user for a series of numbers, until the user enters a period. Main should create an ArrayList of these Integers and call smallestNumber to find the smallest number and print it. Compile and test your code in NetBeans and then on Hackerrank.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT