In an array of unsorted integers (you may assume the array may contain +ve, -ve and 0s), write a function
int returnNthMax(int[] arr, int n)
int returnNthMax(int[] arr, int n)
which will return the nth Max number. For e.g. if this is given array {2, -4, 5, 6, 0, 7, -1, 10, 9} and n=1, it should return the max number, 10 and if n=3, it should return 3rd max number, which is: 7.
package com.zhuyu_deng.test; public class Test { public static void main(String args[]) { int[] a = {-2,11,-4,13,-5,-2}; int[] b = {-2,11,-4,13,-5,-2}; Arrays.sort(a); for (int x : a) System.out.print(x + " "); System.out.println(); for (int i = 0; i < a.length; ++i) { int ans = findNthNumber(b, 0, a.length-1, i); System.out.print(ans + " "); } } public static int findNthNumber(int[] x, int left, int right, int n) { if (left >= right) return x[left]; int m = partition(x, left, right); if (m == n) return x[m]; else if (m > n) return findNthNumber(x, left, m-1, n); else return findNthNumber(x, m+1, right, n); } private static int partition(int[] x, int left, int right) { int m = left; for (int i = left + 1; i <= right; ++i) { if (x[i] < x[left]) { int t = x[i]; x[i] = x[++m]; x[m] = t; } } int t = x[left]; x[left] = x[m]; x[m] = t; return m; } }
public class findkthelement { public static int selectKthLargest(int[] arr, int k) { //ensure k is valid if (k < 1 || k > arr.length){ return -1; } return findKthLargest(arr, 0, arr.length-1, k); } public static int findKthLargest(int[] nums, int start, int end, int k){ int pivot = start; int left = start; int right = end; while (left <= right){ while (left <= right && nums[left] <= nums[pivot]) ++left; while (left<= right && nums[right]>= nums[pivot]) --right; if (left < right){ swap(nums, left, right); } } swap(nums, pivot, right); /* code to find the kth largest element */ if (k == nums.length - right) return nums[right]; else if (k > nums.length -right) return findKthLargest(nums, start, right-1, k); else return findKthLargest(nums, right+1, end, k); /****** code to find the kth smallest element -- * put here to show the slight difference between returning kth smallest * and kth largest if (k == right+1) return nums[right]; else if (k > right+1) return findKthLargest(nums, right+1, end, k); else return findKthLargest(nums, start, right-1, k); */ } private static void swap(int[] nums, int a, int b){ int temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; } public static void main(String[] args) { int[] array = {2, -4, 5, 6, 0, 7, -1, 10, 9}; int k = 6; System.out.print("{"+ array[0]); for (int i = 1; i < array.length;++i) System.out.print(", " + array[i]); System.out.println("}"); System.out.println(k+"th largest element: " + selectKthLargest(array, k)); System.out.print("{"+ array[0]); for (int i = 1; i < array.length;++i) System.out.print(", " + array[i]); System.out.println("}"); } }