提交 523ae792 编写于 作者: L liu13

20190302

上级 028e1405
package code;
/*
* 242. Valid Anagram
* 题意:字符串t是否为s打乱后的重排列
* 难度:Easy
* 分类:Hash Table, Sort
* 思路:
* Tips:
*/
public class lc242 {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()) return false;
int[] chs = new int[26];
for(int i=0; i<s.length(); i++){
chs[s.charAt(i)-'a']++;
}
for(int i=0; i<t.length(); i++){
chs[t.charAt(i)-'a']--;
if(chs[t.charAt(i)-'a']<0) return false;
}
return true;
}
}
package code;
/*
* 268. Missing Number
* 题意:找出 0~n 中少的那个数
* 难度:Easy
* 分类:Array, Math, Bit Manipulation
* 思路:两种巧妙的方法,时间空间都是O(1)
* 异或
* 求和以后,减去所有
* Tips:
*/
public class lc268 {
public int missingNumber(int[] nums) {
int res = nums.length*(nums.length+1)/2;
for(int i:nums) res-=i;
return res;
}
public int missingNumber2(int[] nums) {
int res = nums.length;
for(int i=0; i<nums.length; i++) res^=i^nums[i];
return res;
}
}
\ No newline at end of file
package code;
/*
* 326. Power of Three
* 题意:判断该数是否为3的幂
* 难度:Easy
* 分类:Math
* 思路:除以3,除到不能整除,判断是否为1
* Tips:
*/
public class lc326 {
public boolean isPowerOfThree(int n) {
if (n < 1) return false;
while (n % 3 == 0) n /= 3;
return n == 1;
}
public boolean isPowerOfThree2(int n) {
if(n==1) return true;
double d = n;
while(d>1){
d=d/3;
if(d==1) return true;
}
return false;
}
}
package code;
/*
* 329. Longest Increasing Path in a Matrix
* 题意:寻找最长的递增路径
* 难度:Hard
* 分类:Depth-first Search, Topological Sort, Memoization
* 思路:带记忆的dfs,之前计算的最优解可以直接合并
* Tips:
*/
public class lc329 {
public int longestIncreasingPath(int[][] matrix) {
if(matrix.length==0) return 0;
int[][] cache = new int[matrix.length][matrix[0].length]; //存储计算过的结果
int res = 0;
for (int i = 0; i < matrix.length ; i++) {
for (int j = 0; j < matrix[0].length ; j++) {
res = Math.max(dfs(matrix, i, j, cache), res);
}
}
return res;
}
public int dfs(int[][] matrix, int i, int j, int[][] cache){
int max = 1;
if(cache[i][j]!=0) return cache[i][j];
if( i>0 && matrix[i-1][j]>matrix[i][j]) max = Math.max(dfs(matrix, i-1, j, cache)+1, max);
if( j>0 && matrix[i][j-1]>matrix[i][j]) max = Math.max(dfs(matrix, i, j-1, cache)+1, max);
if( i+1<matrix.length && matrix[i+1][j]>matrix[i][j]) max = Math.max(dfs(matrix, i+1, j, cache)+1, max);
if( j+1<matrix[0].length && matrix[i][j+1]>matrix[i][j]) max = Math.max(dfs(matrix, i, j+1, cache)+1, max);
cache[i][j] = max;
return max;
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册