This commit is contained in:
fanxb 2021-06-15 14:17:00 +08:00
parent 2ffcfa0617
commit 1b4e864ca9
4 changed files with 137 additions and 0 deletions

View File

@ -0,0 +1,41 @@
package com.fanxb.common;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA
* x 的平方根
* 地址 https://leetcode-cn.com/problems/sqrtx/
* 思路 双路规避排序查找
*
*
* @author fanxb
* Date: 2020/6/11 9:56
*/
public class Q1449 {
public String largestNumber(int[] cost, int target) {
int[] f = new int[target + 1];
Arrays.fill(f, Integer.MIN_VALUE);
f[0] = 0;
for (int i = 1; i <= 9; i++) {
int u = cost[i - 1];
for (int j = u; j <= target; j++) {
f[j] = Math.max(f[j], f[j - u] + 1);
}
}
if (f[target] < 0) return "0";
StringBuilder ans = new StringBuilder();
for (int i = 9, j = target; i >= 1; i--) {
int u = cost[i - 1];
while (j >= u && f[j] == f[j - u] + 1) {
ans.append(i);
j -= u;
}
}
return ans.toString();
}
public static void main(String[] args) {
System.out.println(new Q1449().largestNumber(new int[]{4,3,2,5,6,7,2,5,5},9));
}
}

View File

@ -0,0 +1,30 @@
package com.fanxb.common;
/**
* Created with IntelliJ IDEA
*
* @author fanxb
* Date: 2020/6/11 9:56
*/
public class Q278 {
private boolean isBadVersion(int n){
return true;
}
public int firstBadVersion(int n) {
int left=1,right=n;
while (left<right){
int mid =(int) ((long)left+right>>1);
if(isBadVersion(mid)){
right=mid;
}else{
left=mid+1;
}
}
return left;
}
public static void main(String[] args) {
System.out.println(new Q278().firstBadVersion(16));
}
}

View File

@ -0,0 +1,31 @@
package com.fanxb.common;
/**
* 两数相加
*
* @author fanxb
* @date 2021/6/1
**/
public class Q374 {
private static int target=6;
private static int guess(int num){
return Integer.compare(target, num);
}
public int guessNumber(int n) {
int l=1,r=n;
while (l<r){
int mid = l+(r-l)/2;
if(guess(mid)==1){
l=mid+1;
}else{
r=mid;
}
}
return l;
}
public static void main(String[] args) {
System.out.println(new Q374().guessNumber(10));
}
}

View File

@ -0,0 +1,35 @@
package com.fanxb.common;
/**
* 两数相加
*
* @author fanxb
* @date 2021/6/1
**/
public class Q852 {
public int peakIndexInMountainArray(int[] arr) {
int l=0,r=arr.length-1;
while (l<r){
int mid = l+(r-l)/2;
if(arr[mid]==arr[mid+1]){
//无法判断mid处于什么位置
if(arr[l]<=arr[mid]){
l++;
}else{
r--;
}
}else if(arr[mid]>arr[mid+1]){
//说明是递减的
r=mid;
}else{
//说明是递增的
l=mid+1;
}
}
return l;
}
public static void main(String[] args) {
System.out.println(new Q852().peakIndexInMountainArray(new int[]{0,10,5,2}));
}
}