题解 | #二分查找-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);
        }
    }
}

#算法##算法笔记#
算法代码编程 文章被收录于专栏

算法代码编程

全部评论

相关推荐

03-02 08:18
集美大学 Java
钱嘛数字而已:没有赛事奖项么?另外,项目经历字有点多哈,建议突出一下重点:用的什么技术,解决什么问题,达到什么效果。
大家都开始春招面试了吗
点赞 评论 收藏
分享
牛客51274894...:照片认真的吗,找个专门拍证件照的几十块钱整端正点吧,要不就别加照片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务