标签:
Question:
Given an integer array, find out the second largest item.
Analysis:
Sort the array (ascending) first. The second largest will be the last but one? Too young, too simple, sometimes naive. It will not work if there are duplicated times. E.g. [2,5,8,3,8,7].
We can use two indicators, li (largest item index, set to 0 initially) and slii (second largest item index, set to -1 initially). Traverse the array, starting from the second item in the array, let lii store the largest item‘s index, slii store the second largest one‘s. It can complete in O(n).
Code:
public static int findSecondLargest(final int[] array) { if (array != null && array.length >= 2) { int lii = 0; int slii = -1; for (int i = 1; i < array.length; i++) { if (array[i] > array[lii]) { slii = lii; lii = i; } else if (array[i] == array[lii]) { continue; } else { slii = (slii == -1 || array[slii] < array[i]) ? i : slii; } return slii; } return -1; }
So far so good.
Question:
Given an integer array, find out the third largest item.
Analysis:
WTH? Use three indicators, lii, slii, tlii (third largest item index).
public static int findThirdLargest(final int[] array) { if (array != null && array.length >= 3) { int lii = 0; int slii = -1; int tlii = -1; for (int i = 1; i < array.length; i++) { if (array[i] > array[lii]) { tlii = slii; slii = lii; lii = i; } else if (array[i] == array[lii]) { continue; } else { if (slii == -1) { slii = i; } else { if (array[i] > array[slii]) { tlii = slii; slii = i; } else if (array[i] == array[slii]) { continue; } else { tlii = (tlii == -1 || array[tlii] < array[i]) ? i : tlii; } } } } return tlii; } return -1; }
It smells. I‘m kind of repeating myself.
Question:
Given an integer array, find out the ith largest item.
Analysis:
WTF? Use i indicators? Write i methods? Don‘t repeat yourself (DRY). To find out the ith largest item, we use an assistant array indicators.
public static int findithLargest(final int ith, final int[] array) { if (array == null || ith < 1 || array.length < ith) { return -1; } int[] inidcators = new int[ith]; for (int i = 1; i < ith; i++) { inidcators[i] = -1; } for (int i = 1; i < array.length; i++) { updateIndices(i, array, 0, inidcators); } return inidcators[ith - 1]; } private static void updateIndices(final int cur, final int[] array, final int ithlii, int[] inidcators) { if (ithlii < inidcators.length) { if (inidcators[ithlii] == -1) { inidcators[ithlii] = cur; } else if (array[cur] > array[inidcators[ithlii]]) { for (int i = inidcators.length - 1; i > ithlii; i--) { inidcators[i] = inidcators[i - 1]; } inidcators[ithlii] = cur; } else if (array[cur] == array[inidcators[ithlii]]) { return; } else { updateIndices(cur, array, ithlii + 1, inidcators); } } }
Find ith largest array in an array
标签:
原文地址:http://www.cnblogs.com/kerneloops/p/4576412.html