【Java】値にindexを持たせて格納する(B - Palace)
解いた問題
AtCoderの「B - Palace」
提出した回答
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int T = sc.nextInt(); int A = sc.nextInt(); Map<Integer, Double> map = new HashMap<>();//index,Aとの気温差 int minKey = 0; double minValue = 0; for (int i = 1; i <= N; i++) { map.put(i, Math.abs((T - sc.nextInt() * 0.006) - A )); if (i == 1) { minKey = 1; minValue = map.get(1); continue; } if (map.get(i) < minValue) { minKey = i; minValue = map.get(i); } } System.out.println(minKey); sc.close(); } }
「地点の番号を出力する」ため、for文でindexを格納する必要があった。Listでは出来ない(思いついていない)ので、HashMapを使った。
for文の「i」(index)と入力された値をセットで格納している。
値は、問題通りの計算に加え、Aとの絶対値を計算してから格納している。
あとは各「i」の値で「i-1」の値と比べ、小さい値(Aと近い値)を採用する。
TODO
- 他のA,B問題を解く
おわり。。