Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LC 704.二分查找⭐⭐⭐⭐ #15

Open
HealUP opened this issue May 10, 2023 · 0 comments
Open

LC 704.二分查找⭐⭐⭐⭐ #15

HealUP opened this issue May 10, 2023 · 0 comments
Labels
算法 记录刷题记录,代码随想录

Comments

@HealUP
Copy link
Owner

HealUP commented May 10, 2023

704.二分查找🤓🤓
思路分析:

二分查找法是一种在有序数组中查找某一特定元素的搜索算法。搜索过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜索过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半

public int binarySearch(int[] nums, int target) {
        // 在区间[left,right]中查找元素,左闭右闭
        int left = 0;
        int right = nums.length - 1;

        // 由于是在区间[left,right]中查找
        // 因此当left=right时,区间内还有一个元素需要查找
            while (left <= right) {
            // 计算中间点
            int mid = left + (right-left)/2;

            // 如果target == nums[mid]则表示已经找到,返回mid
            if (target == nums[mid]) {
                return mid;
                // 如果target < nums[mid],表示目标值可能在左半边
            } else if (target < nums[mid]){
                // 由于是在左闭右闭的区间[left,right]中查找
                // 而target < nums[mid],因此mid不再需要考虑
                // 所以right = mid - 1,即在[left,mid-1]中继续查找
                right = mid - 1;

                // 如果target > nums[mid],表示目标值可能在右半边
            } else if (target > nums[mid]){
                // 由于是在左闭右闭的区间[left,right]中查找
                // 而target > nums[mid],因此mid不再需要考虑
                // 所以left = mid + 1,即在[mid+1,right]中继续查找
                left = mid + 1;
            }
        }

        // 未找到返回-1
        return -1;
    }
@HealUP HealUP added 算法 记录刷题记录,代码随想录 二分查找 labels May 10, 2023
@HealUP HealUP changed the title 二分查找⭐⭐⭐⭐ 一维数组⭐⭐⭐⭐ May 10, 2023
@HealUP HealUP changed the title 一维数组⭐⭐⭐⭐ LC 704.二分查找⭐⭐⭐⭐ May 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 记录刷题记录,代码随想录
Projects
None yet
Development

No branches or pull requests

1 participant