题目主要信息

1、第n行第一个偶数出现的位置。如果没有偶数,则输出-1。例如输入3,则输出2,输入4则输出3。

2、多组输入

方法一:数学方法

具体方向

我们可以通过规律来求解,写出几行后,可以发现除前两行,从第三行开始奇数行的偶数就在第二个,偶数行的偶数要么在第4个要么在第3个,关键看能不能整除4。

alt

Java代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()){
            int num = sc.nextInt();
            if(num == 1 || num == 2){
                System.out.println(-1);
            }else {
                if(num % 2==1){
                    System.out.println(2);
                }else  if(num %4 == 2){
                    System.out.println(4);
                }else {
                    System.out.println(3);
                }
            }
        }
    }
}

复杂度分析

  • 时间复杂度:O(1)O(1),直接找,常数时间
  • 空间复杂度:O(1)O(1),无额外空间

方法二:找规律

具体方法

举例 alt

alt

alt

alt

我们可以发现输入的数字-3后对4取余可以得到第一个偶数位置在哪。

Java代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int []num = {2,3,2,4};
        while (sc.hasNext()){
            int n = sc.nextInt();
            if(n<3){
                System.out.println(-1);
            }else {
                System.out.println(num[(n-3)%4]);
            }
        }
    }
}

复杂度分析

  • 时间复杂度:O(1)O(1),直接从数组中找
  • 空间复杂度:O(1)O(1),一个常数级的数组。