程式碼隨想錄演算法訓練營第一天| 704. 二分查詢、27. 移除元素。

jeasonGo發表於2024-03-06

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;
    int index = (minIndex + maxIndex)/2;
    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不僅是慢指標,同時也攜帶了新陣列的長度資訊

相關文章