Question

2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert all elements of array in a haimport java.util.Arrays; import java.util.HashSet; public class Lab2 public static void main(String [largs) int[] arr-1, 5, 3

2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert all elements of array in a hashtable For every element in array: counter0 a. b. c. .Look for array[i] . Look for array [幻 + k in the hash map, if found then increment counter. -k in the hash map, if found then increment counter. Remove arrayli] from hash table. d. return counter For example: Input : array[] {1, 5, 3, 4, 2), k 3 Output: 2 Explanation: There are 2 pairs with difference 3, the pairs are (4, 1) and 15, 2)
import java.util.Arrays; import java.util.HashSet; public class Lab2 public static void main(String [largs) int[] arr-1, 5, 3, 4, 2}; int k = 3; long start = System .currentTimem llis(); System.out.println("Count is "+ solve_with_Hash(arr,k)); // should be 2 System.out.println("Total execustion time (taken by solve_with_Hash):" +(System.currentTimeMiLlis()-start)); start System.currentTimeMiLLis); System.out.println("InInCount is "+ 5olvewith Soct (arr,k)); / should be 2 System.out.println("Total execustion time (taken by solve_with_Sort):" +(System.currentTimeMiLlis()-start)); public static int solve_with_Hash(int[] arr, int k) int counter = 0; HashSet
0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.*;
import java.io.*;

public class Main
{


    public static int solve_with_Hash(int arr[],int k)
    {

        int count=0;

        // create hash set


        HashSet<Integer> hs=new HashSet<>();


        for (int i:arr)
        {

            hs.add(i);
        }
      //iterator for hashset
        Iterator <Integer>itr = hs.iterator();

        while(itr.hasNext())
        {
     
            int p=(int)itr.next();

            if(hs.contains(p+k))
                count++;
            if(hs.contains(p-k))
                count++;
            // remove element
            itr.remove();


        }


       return count;






    }

    public static void main(String args[]) throws Exception
    {

      int[] arr={1,5,3,4,2};
      int k=3;

// function call
        System.out.println("\n\n count is : "+solve_with_Hash(arr,k));

    }
}

Sample Run:

sample IC: n,java [samplel- Intelliü IDEA Eie Edit צ¡ew Navigate gode Analyze Befactor Build Run lools VCs window Help sample

Please upvote me...

for any query plzz comment ;)

Add a comment
Know the answer?
Add Answer to:
2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert a...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (JAVA) Given an array of unique positive integers, write a function findSums that takes the array...

    (JAVA) Given an array of unique positive integers, write a function findSums that takes the array input and: 1. Creates a hashtable called “hashT” and inserts all the elements of the input array in the hashtable. 2. Finds pairs of elements in the hashtable whose sum is another element (sum) in the hashtable and print the pairs in the console. 3. Returns another hashtable names “sums” of those sum elements. For example: Input: [1,5,4,6,7,9] Output: [6,5,7,9] Explanation: 6 = 1...

  • I need to program 3 and add to program 2 bellows: Add the merge sort and...

    I need to program 3 and add to program 2 bellows: Add the merge sort and quick sort to program 2 and do the same timings, now with all 5 sorts and a 100,000 element array. Display the timing results from the sorts. DO NOT display the array. ____________________>>>>>>>>>>>>>>>>>>>>___________________________ (This is program 2 code that I did : ) ---->>>>>> code bellow from program 2 java program - Algorithms Write a program that randomly generates 100,000 integers into an array....

  • must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int...

    must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int [] arr); public static void quickSort(int [] arr); public static void mergeSort(int [] arr); The quick sort and merge sort must be implemented by using recursive thinking. So the students may provide the following private static methods: //merge method //merge two sorted portions of given array arr, namely, from start to middle //and from middle + 1 to end into one sorted portion, namely,...

  • public static int[] collatz(int start, int numIterations) Given integer start and integer numIterations, return an array...

    public static int[] collatz(int start, int numIterations) Given integer start and integer numIterations, return an array containing the Collatz sequence beginning with start up to numIterations. The Collatz function is defined by: 3n + 1 if n is odd n/2 if n is even Given start = 7 and numIterations = 3, this method returns [7, 22, 11, 34] TESTING: collatz(7,3) should return {7, 22, 11, 34} collatz(6,0) should return {6} collatz(6, 5) should return {6, 3, 10, 5, 16,...

  • Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr,...

    Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr, int count, int key ) { 1: find the index of the first occurance of key. By first occurance we mean lowest index that contains this value. hint: copy the indexOf() method from Lab#3 into the bottom of this project file and call it from inside this remove method. The you will have the index of the value to remove from the array 2:...

  • Need some help on homework practice problems, Thank you in advance! Problem 1: Write a method,...

    Need some help on homework practice problems, Thank you in advance! Problem 1: Write a method, parallelSum(), that uses the fork-join framework to compute the sum of the elements of an array. Its skeleton as well as its Javadoc is provided in the file ParallelSum.java. Simple code for testing and timing your method is also provided in the main method. This problem is essentially the same as ParallelMax in structure. Therefore, follow the code for ParallelMax to complete ParallelSum. Problem...

  • Create an ArrayListReview class with one generic type to do the following • Creates an array...

    Create an ArrayListReview class with one generic type to do the following • Creates an array list filled with the generic type of the ArrayListReview class, and inserts new elements into the specified location index-i in the list. (5 points) • Create a method inside the class to implement the calculation of Fibonacci numbers. Use System.nanoTime to find out how much time it takes to get fab(50). Create a method inside the class to check if an array list is...

  • Ch. 09: Exclusive find in Array (Arrays, conditional, counter) Write a method that will receive an...

    Ch. 09: Exclusive find in Array (Arrays, conditional, counter) Write a method that will receive an array of integers and an integer value as a parameter. The integer value received as the second parameter will be searched within the Array received as the other parameter. The method will return true if the value appears only once in the Array. Use the "documentation shown in the program as a guide". As an example, if the array received was the sequence of...

  • Display all the distinct numbers and their frequencies in the array. Hint: Use a map. STARTER...

    Display all the distinct numbers and their frequencies in the array. Hint: Use a map. STARTER CODE: import java.util.HashMap; public class NumberFrequncies {    public static void main(String[] args) {        int[] numbers = {2, 3, 0, 1, -1, 9, 10, 10, 9, 3, 0, 2};               //TODO: ------------        /* Add code below to store the distinct numbers and their count        * in a data structure called numberFrequencyMap        */   ...

  • import java.util.Arrays; public class lab {    public static void main(String args[])    {    int...

    import java.util.Arrays; public class lab {    public static void main(String args[])    {    int arr[] = {10, 7, 8, 9, 1, 5,6,7};    int arr2[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};    int arr3[] = {1, 3, 5, 3, 2, 6, 20};    quicksort(arr,0,arr.length-1);    quicksort(arr2,0,arr2.length-1);    quicksort(arr3,0,arr3.length-1);    System.out.println(Arrays.toString(arr));    System.out.println(Arrays.toString(arr2));    System.out.println(Arrays.toString(arr3));       }    private static int partition(int[] items,int low, int high)    {    int i=0;    int j=0;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT