Question

Question: I am using three different ways to execute this program. I am a bit confused...

Question: I am using three different ways to execute this program. I am a bit confused on the time complexity for each one. Can someone explain the time complexity for each function in relation to the nanoseconds.

import java.util.HashMap;
import java.util.Map;
public class twosums {
  
   public static void main(String args[]) {
      
       int[] numbers = new int[] {2,3,9,4,8};;
       int target = 10;
      
       long nano_begin1 = System.nanoTime();
       int[] result1 = twoSums(numbers,target);
       long nano_end1 = System.nanoTime();
      
       long nano_begin2 = System.nanoTime();
       int[] result2 = twoSums2(numbers,target);
       long nano_end2 = System.nanoTime();
      
       long nano_begin3 = System.nanoTime();
       int[] result3 = brutForce(numbers,target);
       long nano_end3 = System.nanoTime();
      
       System.out.println("Two Sums using one pass: " + result1[0] + " " + result1[1] + " -> "+ (nano_end1 - nano_begin1));
   System.out.println("Two Sums using two pass: " + result2[0] + " " + result2[1] + " -> "+ (nano_end2 - nano_begin2));
   System.out.println("Brut Force: " + result3[0] + " " + result3[1] + " -> " + (nano_end3 - nano_begin3));
      
   }
  
   public static int [] brutForce(int[] nums, int target) {
      
      
       for(int i = 0; i < nums.length; i++) {
          
           for(int j = i + 1; j < nums.length; j++) {
              
               if(nums[j] == target - nums[i]){
                  
                   return new int [] {i,j};
               }
           }
          
       }
      
       throw new IllegalArgumentException("No two sums add up to target number");
      
   }
  
   public static int[] twoSums(int[] nums, int target) {
      
       Map <Integer, Integer> funguy = new HashMap<>();
       for(int i = 0; i < nums.length; i++) {
          
           funguy.put(nums[i], i);
       }
      
       for(int i = 0; i < nums.length; i++) {
          
          
           int complement = 0;
           complement = target - nums[i];
      
           if(funguy.containsKey(complement)) {
              
               return new int[] {i, funguy.get(complement)};
           }
       }
      
       throw new IllegalArgumentException("No two numbers add up to target number!");
      
   }
  
   public static int[] twoSums2(int[] nums, int target) {
      
       Map <Integer, Integer> funguy = new HashMap<>();
       for(int i = 0; i < nums.length; i++) {
          
           int complement = 0;
           complement = target - nums[i];
          
          
           if(funguy.containsKey(complement)) {
              
               return new int[] { funguy.get(complement), i};
           }
          
           funguy.put(nums[i], i);

       }
      
       throw new IllegalArgumentException("No two numbers add up to target number!");
  
  
   }
  
}

Homework Answers

Answer #1

In brute force approach , it is checking all possible pairs in array nums[], whose sum equal to target.
In worst case
let nums.length = n
for(int i = 0; i < nums.length; i++) { ---------runs n times
        
           for(int j = i + 1; j < nums.length; j++) {
            
               if(nums[j] == target - nums[i]){
                
                   return new int [] {i,j};
               }
           }

for i=0 inner loop runs (n-1) times
for i=1 inner loop runs (n-2) times
for i=2 inner loop runs (n-3) times
and so on......

Total run = (n-1) + (n-2) + (n-3) + ........+ 2 + 1
T(n) = n*(n-1)/2 = O(n^2)

twoSums(int[] nums, int target)
A HashMap created which takes n times
and for searching it also take n times
Total run = 2*n

twoSums2(int[] nums, int target)
A HashMap creation and searching both done in single for Loop
Total run = n

order of runtime
Brute Force > twoSums > twoSums2

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
Do a theta analysis and count the number of computations it performed in each function/method of...
Do a theta analysis and count the number of computations it performed in each function/method of the following code: import java.io.*; import java.util.Scanner; class sort { int a[]; int n; long endTime ; long totalTime; long startTime; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public sort(int nn) // Constructor { a = new int[nn]; n = nn; endTime= 0; totalTime =0; startTime =0; } public static void main(String args[]) throws IOException { System.out.print("\nEnter number of students: "); int nn =...
Hello, I am trying to create a Java program that reads a .txt file and outputs...
Hello, I am trying to create a Java program that reads a .txt file and outputs how many times the word "and" is used. I attempted modifying a code I had previously used for counting the total number of tokens, but now it is saying there is an input mismatch. Please help! My code is below: import java.util.*; import java.io.*; public class Hamlet2 { public static void main(String[] args) throws FileNotFoundException { File file = new File("hamlet.txt"); Scanner fileRead =...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class Food {     static int count;     private String flavor = "sweet";     Food() { count++; }     void setFlavor(String s) { flavor = s; }     String getFlavor() { return flavor; }     static public void main(String[] args) {         Food pepper = new Food();         System.out.println(pepper.getFlavor());     } } a. a class variable b. a constructor c. a local object variable d....
In this code, I build a single-linked list using a node class that has been created....
In this code, I build a single-linked list using a node class that has been created. How could I change this code to take data of type T, rather than int. (PS: ignore the fact that IOHelper.getInt won't work for the type T... ie second half of main). Here's my code right now: public class SLList { public SLNode head = null; public SLNode tail = null; public void add(int a) {// add() method present for testing purposes SLNode newNode...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
is there anything wrong with the solution. the question are from java course Write a main...
is there anything wrong with the solution. the question are from java course Write a main method that will request the user to enter Strings using a JOptionPane input dialog. The method should continue accepting strings until the user types “STOP”.       Then, using a JOptionPane message dialog, tell the user how many of the strings begin and end with a digit. Answer: import javax.swing.*; public class IsAllLetters {     public static void main(String[] args) {         String input;         int count =...
I am a beginner when it comes to java codeing. Is there anyway this code can...
I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding? public class Stock { //fields private String name; private String symbol; private double price; //3 args constructor public Stock(String name, String symbol, double price) { this.name = name; this.symbol = symbol; setPrice(price); } //all getters and setters /** * * @return stock name */ public String getName() { return name; } /** * set...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The word the user is trying to guess is made up of hashtags like so " ###### " If the user guesses a letter correctly then that letter is revealed on the hashtags like so "##e##e##" If the user guesses incorrectly then it increments an int variable named count " ++count; " String guessWord(String guess,String word, String pound) In this method, you compare the character(letter)...
I am trying to take a string of numbers seperated by a single space and covert...
I am trying to take a string of numbers seperated by a single space and covert them into a string array. I have created the following code but it only works if the numbers are seperated a a comma or something similar to that. Example of what I am trying to achieve: string input = "1 1 1 1 1" turn it into.... int[] x = {1,1,1,1} so that it is printed as... [1, 1, 1, 1]    This is...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT