1
通过用例43%
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.Scanner; 4 5 public class Main { 6 public static void main(String[] args) { 7 Scanner cin = new Scanner(System.in); 8 while(cin.hasNext()){ 9 int n = cin.nextInt(); 10 int k = cin.nextInt(); 11 12 //输入n个房子各自的价格 输入0表示不可购买 下标为0到(n-1) 13 int[] price = new int[n]; 14 int index0 = -1; 15 ArrayList<Integer> canBuy = new ArrayList<>();//可购买的房子的位置 16 for (int i = 0; i < n; i++) { 17 int tmp = cin.nextInt(); 18 price[i] = tmp; 19 20 if(tmp==0) index0 = i; 21 if(tmp!=0 && tmp <= k) canBuy.add(i); 22 } 23 24 System.out.println(Arrays.toString(price)); 25 System.out.println(canBuy); 26 int min_JuLi = n-1;//定义小美和小团的房子间的初始化最短距离 27 int end = 0;//记录小团最终的选择(房子的编号) 28 29 for (int i = 0; i < canBuy.size(); i++) {//在canBuy中选择与index0间距最小的位置,如果有多个编号,输出编号最小的那个 30 if(Math.abs(canBuy.get(i) - index0)< min_JuLi){ 31 min_JuLi = Math.abs(canBuy.get(i) - index0); 32 end = canBuy.get(i); 33 } 34 } 35 System.out.println(end+1); 36 } 37 } 38 39 }View Code
2
思路:
代码:
3
4