题解 | #二分查找-I#
二分查找-I
https://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b
using System;
using System.Collections.Generic;
using System.Linq;
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param target int整型
* @return int整型
*/
public int search (List<int> nums, int target) {
// write code here
if (nums == null || !nums.Any())
return -1;
int startIndex = 0;
int endIndex = nums.Count - 1;
return this.search(nums, target, startIndex, endIndex);
}
private int search(List<int> nums, int target, int startIndex, int endIndex) {
int middleIndex = (startIndex + endIndex) / 2;
int temp = nums[middleIndex];
if (temp == target)
return middleIndex;
// 处理最后两个数,死循环场景
if (middleIndex == startIndex) {
if (nums[endIndex] == target) {
return endIndex;
} else {
return -1;
}
}
// 递归寻数
if (temp > target) {
return this.search(nums, target, startIndex, middleIndex);
} else {
return this.search(nums, target, middleIndex, endIndex);
}
}
}
#算法##算法笔记#算法代码编程 文章被收录于专栏
算法代码编程
