Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package testrun;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Comparator;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.List;
- import java.util.PriorityQueue;
- class Program {
- public static class Node {
- int x;
- int y;
- int val;
- public int getX() {
- return x;
- }
- public void setX(int x) {
- this.x = x;
- }
- public int getY() {
- return y;
- }
- public void setY(int y) {
- this.y = y;
- }
- public int getVal() {
- return val;
- }
- public void setVal(int val) {
- this.val = val;
- }
- public Node(int x, int y, int val) {
- super();
- this.x = x;
- this.y = y;
- this.val = val;
- }
- }
- public static void KthLargestElem() {
- // matrix is sorted find kth largest,Soltion is klogn
- int mat[][] = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } };
- // create a max heap
- PriorityQueue<Node> minHeap = new PriorityQueue<Program.Node>(new Comparator<Node>() {
- @Override
- public int compare(Node o1, Node o2) {
- return o2.val - o1.val;
- }
- });
- // take required K
- int k = 7;
- // insert last column in max heap;
- for (int i = 0; i < mat.length; i++) {
- minHeap.offer(new Node(i, mat.length - 1, mat[i][mat.length - 1]));
- }
- // replace in max heap from previous column k times
- while (!minHeap.isEmpty()) {
- Node node = minHeap.poll();
- if (k == 1) {
- // output
- System.out.print(node.val);
- }
- if (node.y - 1 >= 0) {
- minHeap.offer(new Node(node.x, node.y - 1, mat[node.x][node.y - 1]));
- }
- k--;
- }
- }
- public static String longestPalindromicSubstring(String str) {
- if (str == null) {
- return null;
- }
- if (str.isEmpty() || str.length() == 1) {
- return str;
- }
- int maxLength = -1;
- String palinDrop = null;
- for (int i = 0; i < str.length(); i++) {
- // even length palindrom check
- int stattingIndex = -1;
- String currentPalindrop = null;
- int low = i - 1;
- int high = i;
- while (low >= 0 && high < str.length() && str.charAt(low) == str.charAt(high)) {
- if (high - low + 1 > maxLength) {
- stattingIndex = low;
- maxLength = high - low + 1;
- }
- low--;
- high++;
- }
- // odd length
- low = i - 1;
- high = i + 1;
- while (low >= 0 && high < str.length() && str.charAt(low) == str.charAt(high)) {
- if (high - low + 1 > maxLength) {
- stattingIndex = low;
- maxLength = high - low + 1;
- }
- low--;
- high++;
- }
- if (stattingIndex > -1 && maxLength > 0) {
- currentPalindrop = str.substring(stattingIndex, stattingIndex + maxLength);
- if (palinDrop == null || currentPalindrop != null && currentPalindrop.length() > palinDrop.length()) {
- palinDrop = currentPalindrop;
- }
- }
- }
- return palinDrop;
- }
- static class MinMaxStack {
- ArrayList<HashMap<String, Integer>> minMaxMap = new ArrayList<HashMap<String, Integer>>();
- ArrayList<Integer> stack = new ArrayList<Integer>();
- public Integer peek() {
- return (stack.get(stack.size() - 1));
- }
- public Integer pop() {
- minMaxMap.remove(minMaxMap.size() - 1);
- int returned = peek();
- stack.remove(stack.size() - 1);
- return returned;
- }
- public void push(Integer number) {
- HashMap<String, Integer> newTempMap = new HashMap<String, Integer>();
- newTempMap.put("min", number);
- newTempMap.put("max", number);
- int currentSieOfMap = minMaxMap.size();
- if (currentSieOfMap > 0) {
- HashMap<String, Integer> lastMinMax = minMaxMap.get(currentSieOfMap - 1);
- newTempMap.replace("min", Math.min(lastMinMax.get("min"), number));
- newTempMap.replace("max", Math.max(lastMinMax.get("max"), number));
- }
- minMaxMap.add(newTempMap);
- stack.add(number);
- }
- public Integer getMin() {
- return minMaxMap.get(minMaxMap.size() - 1).get("min");
- }
- public Integer getMax() {
- return minMaxMap.get(minMaxMap.size() - 1).get("max");
- }
- }
- public static ArrayList<ArrayList<Integer>> powerset(ArrayList<Integer> array) {
- ArrayList<ArrayList<Integer>> pSets = new ArrayList<ArrayList<Integer>>();
- // add empty set
- pSets.add(new ArrayList<Integer>());
- // for each number,get currenct poer set add that number in that set,add
- // new set in power set
- for (int curNum : array) {
- int lengthOfCurrentPowerSet = pSets.size();
- for (int index = 0; index < lengthOfCurrentPowerSet; index++) {
- ArrayList<Integer> curSet = new ArrayList<Integer>(pSets.get(index));
- curSet.add(curNum);
- pSets.add(curSet);
- }
- }
- return pSets;
- }
- public static ArrayList<ArrayList<Integer>> getPermutations(ArrayList<Integer> array) {
- ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
- generatePerm(array, new ArrayList<Integer>(), list);
- return list;
- }
- public static void generatePerm(ArrayList<Integer> array, ArrayList<Integer> currentPer,
- ArrayList<ArrayList<Integer>> finalListOfPermutation) {
- // when current processed array is process and current generated
- // permuation has elements it means we have covered all elements add it
- // in to final list
- if (array.isEmpty() && !currentPer.isEmpty()) {
- finalListOfPermutation.add(currentPer);
- }
- for (int i = 0; i < array.size(); i++) {
- // remove Ith elem from current array
- ArrayList<Integer> newarray = new ArrayList<Integer>(array);
- newarray.remove(i);
- // insert the ith elem in current permutation
- ArrayList<Integer> newperm = new ArrayList<Integer>(currentPer);
- newperm.add(array.get(i));
- // call recursion for this new array and current permutation
- generatePerm(newarray, newperm, finalListOfPermutation);
- }
- }
- public static ArrayList<Integer> riverSizes(int[][] matrix) {
- ArrayList<Integer> riverSizes = new ArrayList<Integer>();
- boolean[][] isVisited = new boolean[matrix.length][matrix[0].length];
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[0].length; j++) {
- if (isVisited[i][j]) {
- continue;
- }
- int currentRiverSize = 0;
- ArrayList<Integer[]> currentNodeList = new ArrayList<Integer[]>();
- currentNodeList.add(new Integer[] { i, j });
- while (currentNodeList.size() > 0) {
- Integer[] curNode = currentNodeList.get(currentNodeList.size() - 1);
- currentNodeList.remove(currentNodeList.size() - 1);
- int x = curNode[0];
- int y = curNode[1];
- if (isVisited[x][y]) {
- continue;
- }
- isVisited[x][y] = true;
- if (matrix[x][y] == 0) {
- continue;
- }
- currentRiverSize++;
- // get four neighbours
- if (x > 0 && !isVisited[x - 1][y]) {
- currentNodeList.add(new Integer[] { x - 1, y });
- }
- if (x < matrix.length - 1 && !isVisited[x + 1][y]) {
- currentNodeList.add(new Integer[] { x + 1, y });
- }
- if (y > 0 && !isVisited[x][y - 1]) {
- currentNodeList.add(new Integer[] { x, y - 1 });
- }
- if (y < matrix[0].length - 1 && !isVisited[x][y + 1]) {
- currentNodeList.add(new Integer[] { x, y + 1 });
- }
- }
- if (currentRiverSize > 0) {
- riverSizes.add(currentRiverSize);
- }
- }
- }
- return riverSizes;
- }
- public static ArrayList<Integer[]> threeNumberSum(int[] array, int targetSum) {
- ArrayList<Integer[]> list = new ArrayList<Integer[]>();
- if (array == null || array.length == 0) {
- return list;
- }
- // threeNumberSum(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 15 }, 18);
- Arrays.sort(array);
- int n = array.length;
- int leftPointer = 0, rightPointer = 0, currentPointer = 0;
- for (int i = 0; i < n - 2; i++) {
- currentPointer = i;
- leftPointer = i + 1;
- rightPointer = n - 1;
- while (leftPointer < rightPointer) {
- if (targetSum == array[rightPointer] + array[currentPointer] + array[leftPointer]) {
- Integer[] triplet = new Integer[] { array[currentPointer], array[leftPointer], array[rightPointer] };
- Arrays.sort(triplet);
- // for (int num : triplet) {
- // System.out.print(" " + num);
- // }
- // System.out.println();
- list.add(triplet);
- rightPointer--;
- leftPointer++;
- } else if (targetSum > array[rightPointer] + array[currentPointer] + array[leftPointer]) {
- leftPointer++;
- } else if (targetSum < array[rightPointer] + array[currentPointer] + array[leftPointer]) {
- rightPointer--;
- }
- }
- }
- return list;
- }
- public static int[] bubbleSort(int[] array) {
- if (array == null) {
- return null;
- } else if (array.length == 0) {
- return array;
- }
- int n = array.length;
- boolean swapped = false;
- for (int i = 0; i < n - 1; i++) {
- swapped = false;
- for (int j = 0; j < n - i - 1; j++) {
- if (array[j] > array[j + 1]) {
- int temp = array[j];
- array[j] = array[j + 1];
- array[j + 1] = temp;
- swapped = true;
- }
- }
- if (!swapped) {
- break;
- }
- }
- for (int i : array) {
- System.out.print("," + i);
- }
- return array;
- }
- public static int[] findThreeLargestNumbers(int[] array) {
- if (array == null || array.length == 0) {
- return null;
- }
- int[] largestThree = { Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE };
- // maintain an array of size 3,which contains max elements traversed so
- // far
- for (int cur : array) {
- // whenever a new element comes and compare this from backward,it is
- // greater than replace it and shift current to previous position
- for (int k = 2; k >= 0; k--) {
- if (largestThree[k] < cur) {
- int temp = largestThree[k];
- largestThree[k] = cur;
- for (int shift = k - 1; shift >= 0; shift--) {
- int t = largestThree[shift];
- largestThree[shift] = temp;
- temp = t;
- }
- break;
- }
- }
- }
- for (int i : largestThree) {
- System.out.print("," + i);
- }
- return largestThree;
- }
- public static int findClosestValueInBst(testrun.BinaryTree.Node tree, int target) {
- if (tree == null) {
- return -1;
- }
- int value = tree.data;
- int rvlaue = 0, lvalue = 0;
- if (tree.data < target && tree.right != null) {
- rvlaue = findClosestValueInBst(tree.right, target);
- } else if (tree.data > target && tree.left != null) {
- lvalue = findClosestValueInBst(tree.left, target);
- }
- return Math.max(value, Math.max(rvlaue, lvalue));
- }
- static class BST {
- public int value;
- public BST left;
- public BST right;
- public BST(int value) {
- this.value = value;
- }
- }
- public static int[] twoNumberSum(int[] array, int targetSum) {
- // Write your code here.
- if (array == null || array.length == 0 || targetSum <= 0) {
- return null;
- }
- Arrays.sort(array);
- List<Integer> list = new ArrayList<Integer>();
- int k = array.length - 1;
- int i = 0;
- int count = 0;
- while (i < array.length && k >= 0 && k > i) {
- if (array[i] + array[k] == targetSum) {
- list.add(array[i]);
- list.add(array[k]);
- i++;
- k--;
- } else if (array[i] + array[k] > targetSum) {
- k--;
- } else {
- i++;
- }
- }
- int[] output = new int[list.size()];
- for (int num : list) {
- System.out.print(" " + num);
- output[count++] = num;
- }
- Arrays.sort(output);
- return output;
- }
- public static ArrayList<Integer[]> fourNumberSum(int[] array, int targetSum) {
- ArrayList<Integer[]> sumArray = new ArrayList<Integer[]>();
- HashSet<HashSet<Integer>> finalReturnSet = new HashSet<HashSet<Integer>>();
- HashMap<Integer, ArrayList<HashSet<Integer>>> mapForSum = new HashMap<Integer, ArrayList<HashSet<Integer>>>();
- if (array == null || array.length == 0) {
- return sumArray;
- }
- //maintain a sum map for two elements
- for (int i = 0; i < array.length; i++) {
- for (int j = i + 1; j < array.length; j++) {
- HashSet<Integer> set = new HashSet<Integer>();
- set.add(i);
- set.add(j);
- int sum = array[i] + array[j];
- if (mapForSum.containsKey(sum)) {
- mapForSum.get(sum).add(set);
- } else {
- ArrayList<HashSet<Integer>> l = new ArrayList<HashSet<Integer>>();
- l.add(set);
- mapForSum.put(sum, l);
- }
- }
- }
- //traverse the map fro cur sum and differnce from traget sum.
- for (int curSum : mapForSum.keySet()) {
- if (curSum < targetSum) {
- int diff = targetSum - curSum;
- if (mapForSum.containsKey(diff) && mapForSum.get(curSum) != null && mapForSum.get(diff) != null) {
- for (HashSet<Integer> firstSet : mapForSum.get(curSum)) {
- for (HashSet<Integer> secondSet : mapForSum.get(diff)) {
- HashSet<Integer> finalset = new HashSet<Integer>();
- finalset.addAll(firstSet);
- finalset.addAll(secondSet);
- if (finalset.size() == 4) {
- finalReturnSet.add(finalset);
- }
- }
- }
- }
- mapForSum.put(curSum, null);
- }
- }
- for (HashSet<Integer> set : finalReturnSet) {
- int count = 0;
- Integer[] cur = new Integer[4];
- for (int num : set) {
- cur[count++] = array[num];
- }
- sumArray.add(cur);
- }
- return sumArray;
- }
- public static int[] subarraySort(int[] array) {
- int[] retArr = new int[] { -1, -1 };
- int minOutOfOrder = Integer.MAX_VALUE;
- int maxOutOfOrder = Integer.MIN_VALUE;
- if (array != null && array.length > 0) {
- for (int i = 0; i < array.length; i++) {
- boolean isOutOfOrder = false;
- if (i == 0) {
- if (array[i] > array[i + 1]) {
- isOutOfOrder = true;
- }
- } else if (i == array.length - 1) {
- if (array[i] < array[i - 1]) {
- isOutOfOrder = true;
- }
- } else if (array[i] > array[i + 1] || array[i - 1] > array[i]) {
- isOutOfOrder = true;
- }
- if (isOutOfOrder) {
- minOutOfOrder = Math.min(minOutOfOrder, array[i]);
- maxOutOfOrder = Math.max(maxOutOfOrder, array[i]);
- }
- }
- if (minOutOfOrder == Integer.MAX_VALUE) {
- return retArr;
- }
- int leftIndex = 0;
- while (array[leftIndex] <= minOutOfOrder) {
- leftIndex++;
- }
- int rightIndex = array.length - 1;
- while (array[rightIndex] >= maxOutOfOrder) {
- rightIndex--;
- }
- retArr[0] = leftIndex;
- retArr[1] = rightIndex;
- }
- return retArr;
- }
- public static int[] largestRange(int[] array) {
- int[] retArr = new int[] { -1, -1 };
- HashMap<Integer, Boolean> numMap = new HashMap<Integer, Boolean>();
- for (int i : array) {
- numMap.put(i, true);
- }
- int maxLength = 0;
- for (int num : array) {
- if (!numMap.containsKey(num)) {
- continue;
- }
- int curLength = -1;
- int left = num - 1;
- int right = num + 1;
- while (numMap.containsKey(left)) {
- left--;
- curLength++;
- }
- while (numMap.containsKey(right)) {
- right++;
- curLength++;
- }
- if (curLength > maxLength) {
- maxLength = curLength;
- retArr = new int[] { left + 1, right - 1 };
- }
- }
- return retArr;
- }
- public static int minRewards(int[] scores) {
- int reward = 0;
- int[] rewards = new int[scores.length];
- Arrays.fill(rewards, 1);
- for (int i = 1; i < scores.length; i++) {
- if (scores[i] > scores[i - 1]) {
- rewards[i] = rewards[i - 1] + 1;
- }
- }
- for (int i = scores.length - 2; i >= 0; i--) {
- if (scores[i] > scores[i + 1]) {
- rewards[i] = Math.max(rewards[i], rewards[i + 1] + 1);
- }
- }
- for (int num : rewards) {
- System.out.print(" " + num);
- reward += num;
- }
- return reward;
- }
- public static void main(String[] args) {
- // minRewards(new int[] { 8, 4, 2, 1, 3, 6, 7, 9, 5 });
- KthLargestElem();
- System.out.println();
- }
- }
Add Comment
Please, Sign In to add comment