LeetCode | 704 BinarySearch

Neking發表於2024-07-31

https://github.com/dolphinmind/datastructure/tree/datastructure-array

主類

package com.github.dolphinmind.array.binarysearch;

/**
 * @author dolphinmind
 * @ClassName BinarySearch
 * @description 704 二分法搜尋
 *              前提條件:有序陣列,且無重複元素
 *              迴圈判斷:專注索引
 *              邏輯判斷:專注值
 *              特殊情況:無結果,返回-1
 *              技巧:mid = left + ((right - left) >> 1)
 * @date 2024/7/31
 */

public class BinarySearch {

    private int left;
    private int right;
    private int mid;

    /**
     * 二分法搜尋:左閉右閉區間
     * 分析:迴圈條件看索引,中間索引採用移位,邏輯判斷條件優先選取目標,迴圈不成立有兜底 -1
     *      
     * @param nums
     * @param target
     * @return
     */
    public int binarySearchRightClose(int[] nums, int target) {
        left = 0;
        right = nums.length - 1;

        while (left <= right) {
            mid = left + ((right - left) >> 1);
            if (target == nums[mid]) {
                return mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else if (target < nums[mid]) {
                right = mid;
            }
        }

        return -1;

    }

    /**
     * 二分法搜尋:左閉右開區間
     * @param nums
     * @param target
     * @return
     */
    public int binarySearchRightOpen(int[] nums, int target) {
        left = 0;
        right = nums.length;

        while (left < right) {
            mid = left + ((right - left) >> 1);
            if (target == nums[mid]) {
                return mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else if (target < nums[mid]) {
                right = mid - 1;
            }
        }

        return -1;

    }



}

測試類

package com.github.dolphinmind.array.binarusearch;

import com.github.dolphinmind.array.binarysearch.BinarySearch;
import org.junit.Test;

/**
 * @author dolphinmind
 * @ClassName ApiTest
 * @description
 * @date 2024/7/31
 */

public class BinarySearchTest {

    /**
     * 找房子編號,不要找房子裡面的內容
     */
    @Test
    public void test_binarySearchRightClose() {

        int[] nums = {-1, 0, 3, 5, 9, 12};
        int target = 9;

        BinarySearch binarySearch = new BinarySearch();
        int result = binarySearch.binarySearchRightClose(nums, target);
        System.out.println("左閉右閉區間選擇:" + result);
    }

    @Test
    public void test_binarySearchRightOpen() {
//        int[] nums = {-1,0,3,5,9,12};
        int[] nums = {};
        int target = 2;

        BinarySearch binarySearch = new BinarySearch();
        int result = binarySearch.binarySearchRightOpen(nums, target);
        System.out.println("左閉右開區間選擇:" + result);
    }
}

相關文章