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
  • 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,...

  • Your task is to go through and implement the methods getBucketIndex, add, get, and remove. Follow...

    Your task is to go through and implement the methods getBucketIndex, add, get, and remove. Follow the comments inside respective methods. import java.util.ArrayList; import java.util.Scanner; public class HashtableChaining<K, V> {    // Hashtable bucket    private ArrayList<HashNode<K, V>> bucket;    // Current capacity of the array list    private int numBuckets;    // current size of the array list    private int size;       public HashtableChaining(int buckets){        bucket = new ArrayList<>();        numBuckets = buckets;   ...

  • 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:...

  • 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        */   ...

  • I have a multithreaded java sorting program that works as follows: 1. A list of double...

    I have a multithreaded java sorting program that works as follows: 1. A list of double values is divided into two smaller lists of equal size 2. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice 3. The two sublists are then merged by a third thread merging thread that merges the two sublists into a single sorted list. SIMPLE EXECUTION >java SortParallel 1000 Sorting is done in 8.172561ms when...

  • 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;...

  • The code snippet below is an example of pass by reference. We also provide a sample...

    The code snippet below is an example of pass by reference. We also provide a sample method setZeroAt, which sets 0 at a position i in the array, to illustrate pass by reference. public class Sample { public static void setZeroAt(int [] arr, int i){ arr[i] = 0; } public static void main(String[] args) { Scanner input = new Scanner(System.in); int sample[] = {1, 2, 3}; setZeroAt(sample, 1); //Now sample looks like {1, 0, 3} } } Write a Java...

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
ADVERTISEMENT