题解 | #二分查找-I#

二分查找-I

https://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @param target int整型 
     * @return int整型
     */
    public int search (int[] nums, int target) {
        // write code here
         if (nums == null){
            return -1;
        } else if (nums.length == 0) {
            return -1;
        }
        int star = 0;
        int end = nums.length - 1;
        // 位移-只知道左边界右移多少就行了
        while (true) {
        
            int i = (end - star) / 2;
            i += star;
            // 刚好就是
            if (target == nums[i]) {
                return i;
                // 在右侧,左边界右移
            }
            // 处理找不到的情况 1 2 3 5 7 8
            else if (star >= end) {
                return -1;
            } else if (target > nums[i]) {
                star = i + 1;
            } else if (target < nums[i]) {
                // 在左侧,右边界左移
                end = i - 1;
            }
        }
    }
}

全部评论

相关推荐

码农索隆:7*24,随时待命,这是去🇷🇺打仗去了啊
点赞 评论 收藏
分享
05-27 14:57
西北大学 golang
强大的社畜在走神:27届真不用急,可以搞点项目、竞赛再沉淀沉淀,我大二的时候还在天天打游戏呢
投递华为等公司10个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:02
ssob上原来真有BOSS啊
硫蛋蛋:这种也是打工的,只不是是给写字楼房东打工
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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