Sqrt(x):点击打开链接
Implement int sqrt(int x)
.
Compute and return the square root of x.
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
class Solution {
/**
* @param x: An integer
* @return: The sqrt of x
*/
public int sqrt(int x) {
if(x<=1){
return x;
}
long start=1;
long end=x;
while(start+1<end){
long mid=start+(end-start)/2;
if(mid*mid==x){
return (int)mid;
}else if(mid*mid<x){
start=mid;
}else{
end=mid;
}
}
if(end*end<=x){
return (int)end;
}else{
return (int)start;
}
}
}
Search Insert Position: 点击打开链接
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume NO duplicates in the array.
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
public class Solution {
/**
* param A : an integer sorted array
* param target : an integer to be inserted
* return : an integer
*/
public int searchInsert(int[] A, int target) {
if(A==null || A.length==0){
return 0;
}
int start=0;
int end=A.length-1;
while(start+1<end){
int mid=start+(end-start)/2;
if(A[mid]==target){
return mid;
}else if(A[mid]<target){
start=mid;
}else{
end=mid;
}
}
if(A[start]>=target){ //如果A[start]=target,start就是所求
return start; //如果A[start]>target,target应该放在start的位置,start还是所求
}else if(A[end]>=target){ //end也是
return end;
}else{ //不然就是放数组最后位置,end+1
return end+1;
}
}
}
Wood Cut:点击打开链接
Given n pieces of wood with length L[i]
(integer array). Cut them into small pieces to guarantee you could have equal or more than k pieces with the same length. What is the longest length you can get from the n pieces of wood? Given L & k, return the maximum length of the small pieces.
You couldn't cut wood into float length.
If you couldn't get >= k pieces, return 0
.
For L=[232, 124, 456]
, k=7
, return 114
.
public class Solution {
/**
*@param L: Given n pieces of wood with length L[i]
*@param k: An integer
*return: The maximum length of the small pieces.
*/
public int woodCut(int[] L, int k) {
if(L==null || L.length==0){
return 0;
}
int max=0;
for(Integer len:L){
max=Math.max(len,max); //遍历数组找到最大值元素,然后在长度1~max上二叉中分
}
int start=1;
int end=max;
while(start+1<end){
int mid=start+(end-start)/2;
if(count(L,mid)>=k){ //只要看最后的总结果数:能在保证大于k的基础上长度尽量长
start=mid;
}else{
end=mid;
}
}
if(count(L,end)>=k){ //因为要尽量长,还是要先考虑end值是不是符合要求,再考虑start值
return end;
}else if(count(L,start)>=k){
return start;
}else{
return 0;
}
}
private int count(int[] L, int len) { //二分到每一个长度len下的能切分木头总个数
int sum = 0;
for (int i = 0; i < L.length; i++) {
sum += L[i]/len;
}
return sum;
}
}