代码随想录算法训练营第一天| 704. 二分查找、27. 移除元素。

704.二分查找
https://leetcode.cn/problems/binary-search/description/

一、左闭右闭
`//左闭右闭

public static int erFen1(int[] nums,int target){
    if (target < nums[0] || target > nums[nums.length-1]){
        return -1;
    }
    int maxIndex = nums.length-1;
    int minIndex = 0;
    //防止溢出,当minIndex和maxIndex都很大时,可能minIndex + maxIndex会超过Interger.MaxValue,所以用下面的写法防止溢出  ,注意-的优先级高于>>,所以要加()
    //int index = (minIndex + maxIndex)/2;
    int index =  minIndex + ((maxIndex - minIndex) >> 1);
    while (minIndex <= maxIndex){
        if (nums[index] == target){
            return index;
        }else {
            if (target > nums[index]){
                minIndex = index + 1;
            }else {
                maxIndex = index - 1;
            }
            index = (minIndex + maxIndex)/2;
        }
    }
    return -1;
}`

二、左闭右开
`//左闭右开

if (target < nums[0] || target > nums[nums.length-1]){
        return -1;
    }
    int maxIndex = nums.length;
    int minIndex = 0;
    while (minIndex < maxIndex){
        int index =  minIndex + ((maxIndex - minIndex) >> 1);
        if (nums[index] == target){
            return index;
        }else {
            if (target > nums[index]){
                minIndex = index + 1;
            }else {
                maxIndex = index;
            }
        }
    }
    return -1;
}`

总结:很简单的题目,关键点在于左闭右闭的while判断条件是<= 而左闭右开的while判断条件时< 左闭右开因为<=没有意义

27. 移除元素
https://leetcode.cn/problems/remove-element/description/

public static int removeElement(int[] nums, int val) {
        int slow = 0;
        for (int fast = 0; fast < nums.length; fast++) {
            if (nums[fast] != val){
                nums[slow] = nums[fast];
                slow++;
            }
        }
        return slow;
    }

总结:快慢指针即可 slow不仅是慢指针,同时也携带了新数组的长度信息

posted @   jeasonGo  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示