int n = Integer.parseInt(br.readLine()); int[] s = newint[n]; String[] tmpS = br.readLine().split(" "); for(int i = 0; i < n; i++) { s[i] = Integer.parseInt(tmpS[i]); } tmpS = null;
int q = Integer.parseInt(br.readLine()); int[] t = newint[q]; String[] tmpT = br.readLine().split(" "); for (int i = 0; i < q; i++) { t[i] = Integer.parseInt(tmpT[i]); } tmpT = null;
int count = 0; for(int i : t) { if (binarySearch(s, i)) { count++; } } System.out.println(count); }
privatestaticbooleanbinarySearch(int[] array, int target){ int left = 0; int right = array.length; while (left < right) { int mid = (left + right) / 2; int temp = array[mid]; if (target < temp) { right = mid; continue; } if (temp < target) { left = mid + 1; continue; } returntrue; } returnfalse; } }
😸 Rubyコード
defbinary_search(arr, a) returnfalseif arr.size <= 1=> && arr.last != a mid = (arr.size/2).floor n = arr[mid]
if a == n returntrue elsif a > n binary_search(arr[mid..-1], a) else binary_search(arr[0..mid-1], a) end end