classWordDictionary{//只需要来查询是否存在,而且单词的长度也有限,所以完全可以建立一个500*26的数组来记录每个位置的单词情况//还有就是是否要以当前字母结尾,所以就是一个字典树,得专门记录一个end的状态,才能统计//就是字典树,但难度还是有的,因为是有一个万能匹配符classWordTree{boolean end =false;WordTree[] next =newWordTree[26];//下一个数组,26个字母,未初始化}privateWordTree root;/** Initialize your data structure here. */publicWordDictionary(){
root =newWordTree();}/** Adds a word into the data structure. */publicvoidaddWord(String word){char[] ss = word.toCharArray();WordTree cur =this.root;for(char ch : ss){int i = ch-97;if(cur.next[i]==null)
cur.next[i]=newWordTree();
cur = cur.next[i];}
cur.end =true;//end设置为true}/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */publicbooleansearch(String word){returnhelp(root,word);}privatebooleanhelp(WordTree cur,String word){if(cur==null)returnfalse;char[] ss = word.toCharArray();for(int j=0; j<ss.length; j++){char ch = ss[j];if(ch=='.'){//当出现万能匹配符时,最多可能有26种可能,都要去尝试for(int i=0; i<26; i++)if(help(cur.next[i],String.valueOf(ss,j+1,ss.length-j-1)))returntrue;returnfalse;}int i = ch-97;if(cur.next[i]==null)returnfalse;
cur = cur.next[i];}return cur.end;}}
10-20 lc453. 最小操作次数使数组元素相等
这是一个数学题
设变量t为最终平衡的数值,而x为我们最小操作数
数值长度为n,和为sum
可以得到 n*t = x*(n-1) + sum (1)
然后对于我们数组中的最小值min,它有这样的等式关系 t - min = x (2)
对于上面的等式,它是必须成立的,设想如果不等于,那么等式要么大于要么小于;大于的话,明显不平衡,小于的话,说明达不到平衡
联立(1)(2)
解得 x = sum - min * n;
classSolution{//n-1个元素增加1//如果每次都不给本轮最大值加,是不是就可以到最终结果了,一个贪心的思路,就总能够达到平衡//那么要求多少轮的话,每一轮都能知道,至少有多少个要加,这个复杂度高,不可能模拟的publicintminMoves(int[] nums){int sum =0;int min =(int)1e9;for(int num: nums){if(num<min) min = num;
sum += num;}return sum-min*nums.length;}}
classSolution{//非负,整个数组就是一个数//所以这个就是一个加1的操作,大数加法,然后因为是数组,所以要考虑进位之后比之前多一位的情况,所以需要准备新数组//于是用List来存储,最终reverse,转换成数组publicint[]plusOne(int[] digits){List<Integer> list =newArrayList<>();int t =1;for(int i=digits.length-1; i>=0; i--){int d = digits[i];
list.add((d+t)%10);
t =(d + t)/10;}if(t!=0) list.add(t);Collections.reverse(list);//因为从低位开始,所以是反着的return list.stream().mapToInt(i->i).toArray();}}