首页 > 其他 > 详细

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

时间:2020-08-16 12:09:56      阅读:74      评论:0      收藏:0      [点我收藏+]

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));
    }
}

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

原文:https://www.cnblogs.com/longlong6296/p/13511828.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!