提交 a5a28faa 编写于 作者: L liu13

20190115

上级 ad113df9
package code;
/*
* 240. Search a 2D Matrix II
* 题意:有序矩阵中搜索值
* 难度:Medium
* 分类:Binary Search, Divide and Conquer
* 思路:两种方法,一种O(mlg(n)),遍历每一行,每行二分查找。另一种O(m+n),从右上角开始移动
* Tips:
*/
public class lc240 {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0)
return false;
int i = 0;
int j = matrix[0].length;
while( i<matrix.length || j>=0 ){
if(matrix[i][j]==target)
return true;
else if(matrix[i][j]>target)
j--;
else
i++;
}
return false;
}
}
package code;
/*
* 279. Perfect Squares
* 题意:给定一个数,求该数最少可以由几个平方数的和组成
* 难度:Medium
* 分类:Math, Dynamic Programming, Breadth-first Search
* 思路:dp[i] = dp[i-j*j] +1
* Tips:
*/
import java.util.Arrays;
public class lc279 {
public static void main(String[] args) {
System.out.println(numSquares(12));
}
public static int numSquares(int n) {
int[] dp = new int[n];
Arrays.fill(dp,Integer.MAX_VALUE);
for (int i = 1; i <= n ; i++) {
for (int j=1; j<=i ; j++) {
if(j*j==i)
dp[i-1] = 1;
if(j*j<i){
dp[i-1] = Math.min(dp[i-1-j*j]+1,dp[i-1]);
}
}
}
return dp[n-1];
}
}
package code;
/*
* 283. Move Zeroes
* 题意:把非0元素移到数组前边,相对位置不变
* 难度:Easy
* 分类:Array, Two Pointers
* 思路:遍历一遍数组,如果这个数非0,就合前边的数字交换
* Tips:
*/
public class lc283 {
public void moveZeroes(int[] nums) {
for (int i = 0, j=0; i < nums.length ; i++) {
if(nums[i]!=0){
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
j++;
}
}
}
}
package code;
/*
* 312. Burst Balloons
* 题意:踩气球,求怎样踩,值最大
* 难度:Hard
* 分类:Divide and Conquer, Dynamic Programming
* 思路:假设第n个气球是最后一个被踩爆,则从第n个气球开始,数组可以分为无前后相关性的两块
* Tips:太难了,弃疗了,不会写。直接粘答案。
*/
public class lc312 {
public static void main(String[] args) {
System.out.println(maxCoins(new int[]{3,1,5,8}));
}
public static int maxCoins(int[] iNums) {
int[] nums = new int[iNums.length + 2];
int n = 1;
for (int x : iNums) if (x > 0) nums[n++] = x;
nums[0] = nums[n++] = 1;
int[][] memo = new int[n][n];
int res = burst(memo, nums, 0, n - 1);
return res;
}
public static int burst(int[][] memo, int[] nums, int left, int right) {
if (left + 1 == right) return 0;
if (memo[left][right] > 0) return memo[left][right];
int ans = 0;
for (int i = left + 1; i < right; ++i)
ans = Math.max(ans, nums[left] * nums[i] * nums[right]
+ burst(memo, nums, left, i) + burst(memo, nums, i, right));
memo[left][right] = ans;
return ans;
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册