本文主要是介绍General Algorithm,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- Y or N
-
- Silly Board Game
-
- String Sorting
-
- Find the smallest char in a string
-
- Integer Sorting
-
- Pairs
-
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;
}
这篇关于General Algorithm的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!