add a code in go

This commit is contained in:
lincongcong 2021-07-21 23:41:58 +08:00
parent 02aaf283e1
commit e63c35b170

View File

@ -38,31 +38,56 @@
OK!我们到这一步就能把这个变种给整的明明白白的了下面我们看一哈程序代码吧也是非常简单的
Java Code:
```java
public static int lowBoundnum(int[] nums,int target,int left, int right) {
while (left <= right) {
//求中间值
int mid = left + ((right - left) >> 1);
//大于目标值的情况
if (nums[mid] > target) {
//返回 mid
if (mid == 0 || nums[mid-1] <= target) {
return mid;
}
else{
right = mid -1;
}
} else if (nums[mid] <= target){
left = mid + 1;
while (left <= right) {
//求中间值
int mid = left + ((right - left) >> 1);
//大于目标值的情况
if (nums[mid] > target) {
//返回 mid
if (mid == 0 || nums[mid-1] <= target) {
return mid;
}
else{
right = mid -1;
}
} else if (nums[mid] <= target){
left = mid + 1;
}
//所有元素都小于目标元素
return -1;
}
//所有元素都小于目标元素
return -1;
}
```
Go Code:
```go
func lowBoundnum(nums []int, target, left, right int) int {
for (left <= right) {
//求中间值
mid := left + ((right - left) >> 1);
//大于目标值的情况
if (nums[mid] > target) {
//返回 mid
if (mid == 0 || nums[mid-1] <= target) {
return mid
}else{
right = mid -1
}
} else if (nums[mid] <= target){
left = mid + 1
}
}
//所有元素都小于目标元素
return -1
}
```
## **找出最后一个小于目标元素的索引**
@ -73,6 +98,8 @@ public static int lowBoundnum(int[] nums,int target,int left, int right) {
查找最后一个小于目标数的元素比如我们的目标数为 7 此时他前面的数为 6最后一个 6 的索引为 5此时我们返回 5 即可如果目标数元素为 12那么我们最后一个元素为 11仍小于目标数那么我们此时返回 8即可这个变种其实算是上面变种的相反情况上面的会了这个也完全可以搞定了下面我们看一下代码吧
Java Code:
```java
public static int upperBoundnum(int[] nums,int target,int left, int right) {
@ -99,6 +126,7 @@ public static int upperBoundnum(int[] nums,int target,int left, int right) {
```
Go Code:
```go
func upperBoundnum(nums []int, target, left, right int) int {