Thursday, March 18, 2021

Common elements in two sorted arrays



import java.util.ArrayList;
import java.util.Arrays;

public class CommonNumbers {

	public static void main(String[] args) {
          int[] array1A = {1, 3, 4, 6, 7, 9};
          int[] array2A = {1, 2, 4, 5, 9, 10};
          Integer[] com = common(array1A,array2A);
          for(int i : com) {
              System.out.println(i);
          }

	}

	public static Integer[] common(int array1[], int array2[]) {
		
		int p1=0,p2=0;
		ArrayList<Integer> list = new ArrayList<>();
		while(p1<array1.length && p2 < array2.length) {
			
			if(array1[p1]  == array2[p2]) {
				list.add(array1[p1]);
				p1++;
				p2++;
			}else if(array1[p1] > array2[p2]) {
				p2++;
			}else {
				p1++;
			}
		}
		Integer[] common = new Integer[list.size()];
		return list.toArray(common);
	}
}

Output:-

1 4 9

Wednesday, March 17, 2021

How to find pair of two numbers that's multiply equals to Key

  

    import java.util.ArrayList;

    public class FindPair {

        public static void main(String[] args) {
            int arr[] = {1,2,4,6,3,5}; 
            int key = 20; 
            findPair(arr,key);


        }

        private static void findPair(int[] arr, int key) {
            ArrayList<Integer> numbers = new ArrayList<>();
            boolean status = false;
            for(int num : arr) {

                int anotherNumber = (key/num);
                if(numbers.contains(anotherNumber) && (anotherNumber*num) == key) {
                    status=true;
                    System.out.println("Pair Found: "+"( "+anotherNumber+", "+ num+" )"); 
                }
                numbers.add(num);
            }
            if(!status)
                System.out.print("No such pair"); 

        }

    }

Output:-

Pair Found:- (4,5)

Most Frequently Occurring Item in an Array

  
  import java.util.HashMap;
  import java.util.Map;

  public class MostOccuranceNumber {

      public static void main(String[] args) {

          int[] array1 = {1,2,4,1,3,6,1};
          System.out.println(mostOccurance(array1));

      }
      public static Integer mostOccurance(int ...array) {
          Integer mostCount=0;
          Map<Integer,Integer> map = new HashMap<>();
          Integer mostItem=null;
          for(int i:array) {

              if(map.containsKey(i)) {
                  int counter = map.get(i)+1;
                  map.put(i, counter);
              }else {
                  map.put(i,1);
              }
              if(map.get(i) > mostCount) {
                  mostCount = map.get(i);
                  mostItem = i;
              }
          }
          return mostItem;
      }
  }

Output:-

1

How to sort an HashMap based on value

import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java....