给定一个int型数组,找出其中大于0的数字中倒数第二小的数字的下标
OOP面向对象的思路解法
public class App {
public static int getIndex(int[] array){
List<Integer> positiveNumberList = findPositiveNumbers(array);
int secondSmallest = findSecondSmallestNumber(listToIntArray(positiveNumberList));
return findIndexOfElement(arrayToList(array), secondSmallest);
}
public static List<Integer> arrayToList(int[] array) {
List<Integer> list = new ArrayList<>();
for (int num : array) {
list.add(num);
}
return list;
}
public static int findIndexOfElement(List<Integer> list, int element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == element) {
return i;
}
}
return -1;
}
public static int findSecondSmallestNumber(int[] array) {
Arrays.sort(array);
return array[1];
}
public static int[] listToIntArray(List<Integer> list) {
int[] array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
return array;
}
public static List<Integer> findPositiveNumbers(int[] array) {
List<Integer> positiveNumbers = new ArrayList<>();
for (int num : array) {
if (num > 0) {
positiveNumbers.add(num);
}
}
return positiveNumbers;
}
public static void main(String[] args) {
int[] array = {1, -1, 3, 2, 0};
int index = getIndex(array);
System.err.println(index);
}
}
算法题思路解法
public class T1 {
public static int getIndex(int[] array) {
int secondSmallest = 0;
int positiveCount = 0;
int secondSmallestIndex = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) {
positiveCount++;
if (positiveCount == 2) {
secondSmallest = array[i];
secondSmallestIndex = i;
} else if (positiveCount > 2 && array[i] < secondSmallest) {
secondSmallest = array[i];
secondSmallestIndex = i;
}
}
}
return secondSmallestIndex;
}
public static void main(String[] args) {
int[] array = {1, -1, 3, 2, 0};
int index = getIndex(array);
System.err.println(index);
}
}