1. 程式人生 > 實用技巧 >Finding max and min in arrays Find the index of K min in an array

Finding max and min in arrays Find the index of K min in an array

Implement a method that finds the index of the K-th element equal to the minimum in an array of ints. If no such element can be found, return -1. The input array can be empty, K > 0.

Sample Input 1:

18 4 17 4 19 18 4
2

Sample Output 1:

3

Sample Input 2:

10 15 13 10 14
3

Sample Output 2:

-1
import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static int findIndexOfKMin(int[] numbers, int k) {
        if (numbers.length == 0) {
            return -1;
        }

        int value = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < value) {
                value = numbers[i];
            }
        }

        int counter = 0;

        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == value) {
                counter++;
                if (counter == k) {
                    return i;
                }
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);

        final int k;
        final int[] numbers;

        if (scanner.hasNextInt()) {
            numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
                    .mapToInt(Integer::parseInt)
                    .toArray();
            k = Integer.parseInt(scanner.nextLine());
        } else {
            numbers = new int[0];
            k = 1;
        }

        System.out.println(findIndexOfKMin(numbers, k));
    }
}