public int BinarySearch(int[] A, int target) {
int begin = 0;
int end = A.length;
while (begin < end) {
int mid = (end + begin) / 2;
if (A[mid] == target) {
return mid;
} else if (A[mid] < target) {
begin = mid + 1;
} else {
end = mid;
}
}
return -1;
}
def binary_search(A, target):
begin = 0
end = len(A)
while begin < end:
mid = (begin + end) // 2
if A[mid] == target:
return mid
elif A[mid] < target:
begin = mid + 1
else:
end = mid
return -1
public int BinarySearch(int[] A, int target) {
int begin = 0;
int end = A.length - 1;
while (begin <= end) {
int mid = (end + begin) / 2;
if (A[mid] == target) {
return mid;
} else if (A[mid] < target) {
begin = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
def binary_search(A, target):
begin = 0
end = len(A) - 1
while begin <= end:
mid = (end + begin) // 2
if A[mid] == target:
return mid
elif A[mid] < target:
begin = mid + 1
else:
end = mid - 1
return -1
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.
给定排序数组和目标值,如果找到目标,则返回索引。 如果没有,请返回索引按顺序插入的索引。
您可以假设数组中没有重复项。
Examples:
[1,3,5,6], 5 → 2 ; [1,3,5,6], 2 → 1 ; [1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
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.
public int searchInsert(int[] A, int target) {
int begin = 0;
int end = A.length - 1;
int mid = 0;
while (begin < end) {
mid = (begin + end) / 2;
if (A[mid] == target) {
return mid;
} else if (A[mid] > target) {
end = mid;
} else if (A[mid] < target) {
begin = mid + 1;
}
}
return begin;
}
要注意while循环中begin和end的设置
这是找符合条件的中的上限
def searchInsert(A, target):
begin = 0
end = len(A) - 1
while begin <= end:
mid = (begin + end) // 2
if A[mid] == target:
return mid
elif A[mid] > target:
end = mid - 1
else:
begin = mid + 1
return begin
Implement int sqrt(int x).
Compute and return the square root of x.
实现int sqrt(int x)。
计算并返回x的平方根。
Implement int sqrt(int x).
Compute and return the square root of x.
public int mySqrt(int x) {
if (x <= 1) {
return x;
}
long begin = (long)0;
long end = (long)x / 2 + 1;
while (begin < end) {
long p = (end + begin + 1) / 2;
if (p * p == x) {
return (int)p;
} else if (p * p < x) {
begin = p;
} else {
end = p - 1;
}
}
return (int)begin;
}
这是在符合要求的里面找下限
def mySqrt(x):
if x <= 1:
return x
begin = 0
end = x // 2 + 1
while begin < end:
p = (end + begin + 1) // 2
if p * p == x:
return p
elif p * p < x:
begin = p
else:
end = p - 1
return begin