Y or N
Silly Board Game
2 opponents: A&B. To represent a board by String[] board = new String[]{“…”,”.#.”,”..#”}, then use for loop to get into the board environments(’#‘爲障礙物不可走棋):
. . .
. # .
. . #
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length(); j++) {
.......
}}
已知條件:A 總先走。所以爲了判斷A 的輸贏:用A可選擇走的棋格 數量%2, 如果剩下的棋格爲Even number, A則輸(B贏),否則A贏(B輸)(整個遊戲像抽烏龜,單純以Even/Odd 判斷最後輸贏)。總結爲:先走的,且可走棋數爲Odd的,會成爲最後贏家。
String Sorting
Find the smallest char in a string
Only get the smallest char from the first half of string:
重要條件: Each letter from ‘a’ to ‘z’ will have either zero or two occurrences in s
使用ASCii 去比較字母。
Method 1 (Best)
連續兩次爲最小的直接return.
public class StringHalving {
public String lexsmallest(String s) {
char[] chCount = new char[256];
char smallest = s.charAt(0);
for(int i=0;i<s.length();++i){
if(s.charAt(i)<smallest){
smallest = s.charAt(i);
}
chCount[s.charAt(i)]++;
if(chCount[s.charAt(i)]==2){
return ""+smallest;
}
}
return null;
} }
Method 2 (Easiest)
使用build-in function Array.sort(char [ ])
public class StringHalving {
public String lexsmallest(String s){
int cut = (int) Math.floor(s.length()/2);
char tempArray[] = s.substring(0,cut).toCharArray();
Arrays.sort(tempArray);
return Character.toString(tempArray[0]);
}}
Integer Sorting
Pairs
把已知的數字加一遍K得到Set B,再從已知數字Set A裏找到和Set B重合的數字,累計重合次數
改進:在Set A裏使用Binary Search Tree來找SetB裏所有的數字,並累計
在這題的2叉題目裏,用Hash Table加unordered Set速度快於Ordered過的Set,沒排序過的Set可以增大查找的機率。
#include<iostream>
#include<unordered_set>
using namespace std;
unordered_set<int> s;
int main()
{
int n, k, val;
cin >> n >> k;
for (int i = 0; i < n; i++)
{
cin >> val;
s.insert(val);
}
int ans = 0;
for (unordered_set<int>::iterator it = s.begin(); it != s.end(); ++it)
if (s.find(*it + k) != s.end()) ans++;
cout << ans << endl;
return 0;
}